Reputation: 3526
I am using nodejs for server side connection, I got json object which i posted below, i want to insert that json into mongo based on certain conditions
This is my json:
"_id" : ObjectId("5a1507f7c6e9dc046ee76b01"),
"sendStatus" : false,
"draftName" : "ifelse",
"draftData" : {
"sms" : {
"message" : "Sample",
"sender" : "ifelse"
},
"contacts" : [
{
"selected" : true,
"updatedAt" : "2017-11-18T06:17:32.000Z",
"createdAt" : "2017-11-18T06:17:32.000Z",
"data3" : "",
"data2" : "",
"data1" : "",
"country" : "",
"url" : "",
"company" : "",
"email" : "[email protected]",
"dob" : null,
"postcode" : "",
"region" : "",
"city" : "hhhh",
"street" : "Salai",
"lastName" : "Sameer",
"firstName" : "Mohamed",
"gsm" : "122,
"id" : 1
},
{
"selected" : true,
"updatedAt" : "2017-11-18T06:17:57.000Z",
"createdAt" : "2017-11-18T06:17:57.000Z",
"data3" : "",
"data2" : "",
"data1" : "",
"country" : "",
"url" : "",
"company" : "",
"email" : "[email protected]",
"dob" : null,
"postcode" : "",
"region" : "",
"city" : "",
"street" : "",
"lastName" : "Basha",
"firstName" : "Hameed",
"gsm" : "123450987",
"id" : 2
},
{
"selected" : true,
"updatedAt" : "2017-11-22T04:32:09.000Z",
"createdAt" : "2017-11-22T04:32:09.000Z",
"data3" : "",
"data2" : "",
"data1" : "",
"country" : "",
"url" : "",
"company" : "",
"email" : "[email protected]",
"dob" : null,
"postcode" : "",
"region" : "",
"city" : "",
"street" : "",
"lastName" : "Pandiyan",
"firstName" : "Ganesh",
"gsm" : "213",
"id" : 3
}
]
},
"draftType" : "",
"createdOn" : ISODate("2017-11-22T05:15:35.423Z"),
"updatedOn" : ISODate("2017-11-22T05:15:35.423Z"),
"__v" : 0
I am inserting this data into mongodb, but i want to set one condition,
i want to insert only contacts:[{selected:true}], which having keys as selected:true, if object key is selected:false, i dont want to insert that data into mongodb, Help me.
This is my backend code:
exports.addContactDraft = function (req, res) {
console.log('contactttttttttt', req.body);
var newContactDraft = req.body;
newContactDraft.createdOn = new Date();
newContactDraft.updatedOn = new Date();
new Draft(newContactDraft).save(function (err, data) {
if (err) console.log('new err:', err);
else res.status(200).send(data);
});
}
Upvotes: 0
Views: 72
Reputation: 588
Assuming you only want to filter out the elements from contacts. You can easily filter out unneeded objects from contacts array with array.filter().
Checkout the below code.
var data = {your json object stuff....}
//Filter out the contacts with 'selected=false'
data.draftData.contacts =
data.draftData.contacts.filter(contact=>contact.selected===true);
//Modified contacts that include only the objects with selected property equal to true.
console.log(data);
Upvotes: 1