我使用nodejs进行服务器端连接,我在下面发布了json对象,我想根据某些条件将json插入mongo
这是我的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" : "sameer@gmail.com",
"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" : "ham@gmail.com",
"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" : "gane@gane.com",
"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
我将此数据插入mongodb,但我想设置一个条件,
我想只插入联系人:[{selected:true}],其中包含所选的键:true,如果选择了对象键:false,我不想将该数据插入mongodb,帮帮我。
这是我的后端代码:
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);
});
}
答案 0 :(得分:1)
假设您只想过滤掉联系人中的元素。您可以使用array.filter()轻松地从contacts数组中过滤掉不需要的对象。
查看以下代码。
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);