我必须更新数组中的一个元素,所以我要先提取值,然后再用新数据推送它。 我正在尝试这段代码,并且在pull和push语法中遇到错误。
User.findOneAndUpdate({email:req.user.email}, {$pull: {Addtasks.status : {commonID:req.query.commonIDs}}},
function (error, success) {
if (error) {
console.log(error);
} else {
User.findOneAndUpdate({email:req.user.email}, {$push: {Addtasks.status: req.query.selectedValue}},
function (error, success) {
if (error) {
console.log("Something wrong when updating data!");
} else {
res.redirect('/taskswriter');
console.log("success");
}
});
}
});
下面是Mongoose模式结构。我只想在Addtasks数组中提取元素“状态”,并用新元素推送它。
{
"_id" : ObjectId("5f4217154a5a411a9473d64b"),
"email" : "charlotte@grumpytext.com",
"name" : "Charlotte Miles",
"Addtasks" : [
{
"commonID" : "66k4xorn77x",
"status" : "Requirement Completed",
"Date" : "Sun Aug 23 2020 12:43:57 GMT+0530 (India Standard Time)",
"exampleRadios" : "option1",
"otherdetails" : "bnbn",
"website" : "asad.com",
"keywords" : "anxiety disorders for children, anxiety disorders for adults",
"words" : 12345,
"topic" : "How article is generated?",
"_id" : ObjectId("5f4217354a5a411a9473d64d")
},
{
"commonID" : "offo357aak",
"status" : "Requirement Completed",
"Date" : "Sun Aug 23 2020 12:44:20 GMT+0530 (India Standard Time)",
"exampleRadios" : "option1",
"otherdetails" : "trhr",
"website" : "dsfdd.com",
"keywords" : "Kali from Kaliyug, Kaliki Vishnu Avatar, Vishnu's 10th Avatar",
"words" : 5678,
"topic" : "When the Kaliyug era will end ?",
"_id" : ObjectId("5f42174c4a5a411a9473d651")
}
],
"__v" : 0
}
答案 0 :(得分:1)
我认为您可以使用$set
和位置operator简化为一个查询:
User.findOneAndUpdate({email:req.user.email},
{ $set: { "Addtasks.$" : req.query.selectedValue } })
这将更新第一个匹配的数组元素。如果要更新所有元素,请使用this operator:
User.findOneAndUpdate({email:req.user.email},
{ $set: { "Addtasks.$[]" : req.query.selectedValue } })