only edit (update) fields provided by form into mongoose subdocument - javascript

i wanted to update my mongoose subdocument with whatever field i fill in the form its working fine but the problem i am facing is if any of the field is left empty and then i submit i want it to just update the subdocumnet with just the fields provided by the form and fields which are not provided should be left with what it was before. currently it is deleting the fields not provided by form inside subdocument after the update
this is the update fn i am currently using
List.updateOne(
{"questionSet._id": questId},
{
$set: {
"questionSet.$": req.body
}
},
{new: true, useFindAndModify: false},
(e)=>{
if(e){
console.log(e);
res.redirect("/admin-edit-quest")
} else {
res.redirect("/admin-edit-quest")
}
}
)
this is eg. of my mongoose model
list: { "_id" : ObjectId("60f2cc07275bbb30d8cb268e"),
"listName" : "dsa",
"aboutList" : "dsa queestions",
questionSet" : [ { "solved" : false,
"_id" : ObjectId("60f2cc12275bbb30d8cb2695"),
"topic" : "array",
"name" : "array is best",
"url" : "www.arr.com",
"listname" : "dsa",
"__v" : 0 },
{ "solved" : false,
"_id" : ObjectId("60f2cc1b275bbb30d8cb269d"),
"topic" : "linked list",
"name" : "reverse list",
"url" : "www.list.com",
"listname" : "dsa",
"__v" : 0 }
],
"__v" : 2
}

Need to delete keys with blank values from req.body:
pruned_body = {}
body = JSON.parse(reg.body)
Object.keys(body).forEach(function (key) {
if (body[key]) {
pruned_body[key] = body[key]
}})
And then use pruned_body in $set.

Related

change only one field of entire array of embedded document in mongoose

i have a list schema and a question set schema. the quetsionSet schema is embedded inside the list schema. its working fine but how can i update anything inside the array of embedded document i.e. here i want to change the listname of all the documents inside questionSet (array of questionSet documents).
here is an example of my list document model
{ "_id" : ObjectId("60f2cc07275bbb30d8cb268e"),
"listName" : "dsa",
"aboutList" : "dsa queestions",
questionSet" : [ { "solved" : false,
"_id" : ObjectId("60f2cc12275bbb30d8cb2695"),
"topic" : "array",
"name" : "array is best",
"url" : "www.arr.com",
"listname" : "dsa",
"__v" : 0 },
{ "solved" : false,
"_id" : ObjectId("60f2cc1b275bbb30d8cb269d"),
"topic" : "linked list",
"name" : "reverse list",
"url" : "www.list.com",
"listname" : "dsa",
"__v" : 0 }
],
"__v" : 2
}
you can use the following in your case
db.<collection_name>.updateOne(
{ "_id" : ObjectId("60f2cc07275bbb30d8cb268e")},
{
$set: {
'questionSet.$[].listname': "javascript"
}
}
)

MongoDb - Do i need an index on a second field when using deleteOne

I have a simple collection events
{
"_id" : ObjectId("5e2a9bb9dcb646448f9409b3"),
"year" : 2020,
"employee_id" : "5e1afe5ab7bad92b20365476",
"event" : ["Holidays"],
"total" : 21,
"used" : 1
}
and i don't want to be able to delete the documents that have used field grater than 0.
I use this
db.collection('events').deleteOne({_id: ObjectId("5e2a9bb9dcb646448f9409b3"), used: 0});
Do i need to set an index on used field if i already use _id?
Thanks
Not necessary. MongoDB already uses _id (unique index created by MongoDB) to delete documents.
db.collection('events').find({_id: ObjectId("5e2a9bb9dcb646448f9409b3"), used: 0}).explain();
"winningPlan" : {
"stage" : "FETCH",
"filter" : {
"used" : {
"$eq" : 0.0
}
},
"inputStage" : {
"stage" : "IXSCAN",
"keyPattern" : {
"_id" : 1
},
"indexName" : "_id_",
"isMultiKey" : false,
"multiKeyPaths" : {
"_id" : []
},
"isUnique" : true,
"isSparse" : false,
"isPartial" : false,
"indexVersion" : 2,
"direction" : "forward",
"indexBounds" : {
"_id" : [
"[ObjectId('5e2a9bb9dcb646448f9409b3'), ObjectId('5e2a9bb9dcb646448f9409b3')]"
]
}
}
}

MongoDB - Query nested objects in nested array

I'm kindly requesting your help for this query that I need to do and I'm not very proficient yet in MongoDB. My data structure looks like this:
db.getCollection('EventDateValidation').find({}):
/* 1 */
{
"_id" : ObjectId("5b7b2e3ae5e2100007717d81"),
"_class" : "com.overwatch.common.model.EventDateValidation",
"caseNo" : "OW000002269122201810201135",
"loanNo" : "000002269122",
"eventType" : "BREACLETTR",
"validationStepData" : [
{
"startDate" : {
"isChecked" : "Y",
"comments" : "",
"auditedBy" : "Mahalakshmi M",
"auditedDate" : "2018-12-12"
}
},
{
"completedDate" : {
"isChecked" : "Y",
"comments" : "",
"auditedBy" : "Mahalakshmi M",
"auditedDate" : "2018-12-13"
}
},
{
"deadlineDate" : {
"isChecked" : "Y",
"comments" : "",
"auditedBy" : "Mahalakshmi M",
"auditedDate" : "2018-12-13"
}
}
]
}
/* 2 */
{
"_id" : ObjectId("5b7c11095c2b4d0007bc8c54"),
"_class" : "com.overwatch.common.model.EventDateValidation",
"caseNo" : "OW000000854076201808181158",
"loanNo" : "000000854076",
"eventType" : "FORSALAPPR",
"validationStepData" : [
{
"startDate" : {
"comments" : ""
}
},
{
"completedDate" : {
"comments" : "Received Date = 8/4/2017"
}
},
{
"deadlineDate" : {
"comments" : ""
}
}
]
}
/* 3 */
{
"_id" : ObjectId("5b7ad05d5c2b4d0007bc8631"),
"_class" : "com.overwatch.common.model.EventDateValidation",
"caseNo" : "OW000000873954201810201235",
"loanNo" : "000000873954",
"eventType" : "HUDNOTIFCA",
"validationStepData" : [
{
"startDate" : {
"isChecked" : "Y",
"comments" : "",
"auditedBy" : "Brett Scott",
"auditedDate" : "2018-09-25"
}
},
{
"completedDate" : {
"isChecked" : "Y",
"comments" : "",
"auditedBy" : "Brett Scott",
"auditedDate" : "2018-09-25"
}
},
{
"deadlineDate" : {
"isChecked" : "Y",
"comments" : "",
"auditedBy" : "Brett Scott",
"auditedDate" : "2018-09-25"
}
}
]
}
From this collection, I need to find the documents that have an "auditedDate" in the "deadlineDate". In this example, I would find the documents 1 and 3. Please help me as I'm stuck on this one.
I have tried
db.getCollection('EventDateValidation').find({"validationStepData.deadlineDate.auditedDate":{$exists:true}})
But doesn't seem to work. Help please!
Just for clearing things up: the query in the question works well. I chatted with #Gabriel, and the problem was that Robomongo added hidden non-printable unicode characters to the query.
All in all, for any interested nomads, here are few ways to query an array of objects:
1) Implicit $elemMatch / simple dot notation on an array:
db.getCollection('EventDateValidation').find({"validationStepData.deadlineDate.auditedDate": {$exists:true}})
2) Explicit $elemMatch (we can have multiple query criteria):
db.getCollection('EventDateValidation').find({"validationStepData": { $elemMatch: {"deadlineDate.auditedDate" : {$exists:true} }}})
3) Array dot notation with an index position (when we know the exact position of an element inside an array):
db.getCollection('EventDateValidation').find({"validationStepData.2.deadlineDate.auditedDate": {$exists:true}})
Dot notation wouldn't work since you have an array of objects within validationStepData. You could use $elemMatch to apply your query conditions to the array elements that match your expression.
db.getCollection('EventDateValidation').find({"validationStepData" : { $elemMatch: {"deadlineDate.auditedDate" : {$exists:true} }}})

Mongoose (MongoDB) - Error: Can't use $each with Number

I've to push a given array of Number values into a selected Document inside my MongoDB database.
The Document that I'm going to update as the following structure:
{
"_id" : {
"id" : 17,
"type" : "f"
},
"__v" : 0,
"created_at" : ISODate("2017-03-22T11:16:21.403Z"),
"token" : {
"expDate" : ISODate("2017-12-31T00:00:00Z"),
"token" : "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJlbWFpbCI6ImFsYWRpbkBjb25zb3J6aW9jZXIuaXQiLCJleHAiOjE1MTQ2Nzg0MDB9.QvbT146bA_KH5XA7MH8ASXm9cr3sPZChJ3prYyDireI"
},
"updated_at" : ISODate("2017-07-24T09:42:33.741Z"),
"plots" : {
"idPlot" : [
23570,
23475
]
},
"machines" : [
{
"idPlotBind" : 1,
"ip" : "",
"mac" : "18-5F-00-4A-FE-F4",
"irrId" : 31,
"_id" : ObjectId("59084f527d634d301338aac6"),
"addr" : "pialadin.ddns.net"
},
{
"idPlotBind" : null,
"ip" : "",
"mac" : "12-01-02-FE-AB-B2",
"irrId" : 35,
"_id" : ObjectId("59084f7d7d634d301338aac7")
}
]
}
I'm using the Mongoose library for JS, and the accused query is this one:
userSchema.findOneAndUpdate({$and:[{ '_id.id': resData.PlotRows.IdUser}, {'_id.type': 'f'}]},{$addToSet:{'plots.$.idPlot': {$each: plotData}}}, {upsert: false}, function(err, usr){
if(err){
console.log(err);
return;
}
});
But when I try to execute it, gives me back:
Error: Can't use $each with Number

Unable to print BSON object from javascript

My mongoDB collection looks like this :
{
"_id" : ObjectId("5070310e0f3350482b00011d"),
"emails" : [
{
"_id" : ObjectId("5070310e0f3350482b000120"),
"_type" : "Email",
"name" : "work",
"email" : "peter.loescher#siemens.com",
"current" : true
}
]
}
and this is the .js code i use to print the contents :
c = db.contacts.findOne( { "emails.email" : { $ne : null } }, { "emails" : 1 } )
print(c._id.toString() + " " + c.emails[0]);
when I try to run this javascript file, it is just displaying the id but not the email array.
output:
5070310e0f3350482b00011d [object bson_object]
but when I try c.emails[0].email is is giving proper result. i.e. peter.loescher#siemens.com
All I need is I want to display the whole emails embedded object.
i.e.
"emails" : [
{
"_id" : ObjectId("5070310e0f3350482b000120"),
"_type" : "Email",
"name" : "work",
"email" : "peter.loescher#siemens.com",
"current" : true
}
]
Where I am going wrong?. Any help would be appreciated.
You need printjson to output a nicely formatted JSON:
printjson(c.emails[0]);
Here it is the documentation.

Categories