我想通过索引更新数组中的doc。我的架构和代码看起来像这样
var userSchema = mongoose.Schema({
email: {
type: String,
required: false,
minlength: 4,
trim: true
},
bla: []
});
// this is the example object that I get from the db
{
"id" = "somethingUniq",
"email" = "this@email.workdamnit",
"bla" = [{"blabla": "something"},{"blabla":"somethingelse"}]
}
User.findOneAndUpdate({ "_id": "somethingUniq", "bla.1.blabla": "something" },
{
"$set": { "bla.$.blabla": "something new" },
function(err, doc) {
if (err) console.log('err in update', err);
console.log('doc', doc)
}
})
使索引为1的blabla得到更新。我现在已经试了好几个小时了,但是我尝不起任何东西......
最终结果如下:
{
"_id" = "somethingUniq",
"email" = "this@email.workdamnit",
"bla" = [{"blabla": "something"},{"blabla":"something new"}]
}
答案 0 :(得分:0)
$push
运算符将指定值附加到数组。
(https://docs.mongodb.com/manual/reference/operator/update/push/)
在您的情况下尝试$set
:
User.findOneAndUpdate(
{ "_id": "somethingUniq",
"bla.1.blabla": "something"
},
{ $set:{
"bla.$.blabla": "something new"
}
},
function(err,result){
if (!err) {
console.log(result);
}
});
并确保您在_id
和id
之间使用正确的,因为您在主题中显示了这两者。
如果您正在寻找id
,请同时更改:
"_id": "somethingUniq"
致:
"id": "somethingUniq"