Joh*_*nGa 2 mongoose mongodb node.js
我正在尝试使用Mongoose更新单个文档中的多个字段。
var fooSchema = new Schema({
foo: {
a: [ { type: Number, ref: User, required: true } ],
b: [ { type: Number, ref: User } ],
c: [ { type: Number, ref: User } ],
}
});
foo.findByIdAndUpdate(
req.params._id,
{
$addToSet: { "foo.a" : req.params.user_id },
$pull: { "foo.b" : req.params.user_id },
$pull: { "foo.c" : req.params.user_id }
},
{ safe: true },
function(e) {
...
}
);
Run Code Online (Sandbox Code Playgroud)
foo.a已按预期更新,但未从中删除user_id foo.b。使用Mongoose / MongoDB可以在一次操作中具有多个更新条件吗?
您需要将两个$pull术语合并到一个对象中,因为不能有两个名称相同的字段:
foo.findByIdAndUpdate(
req.params._id,
{
$addToSet: { "foo.a" : req.params.user_id },
$pull: {
"foo.b" : req.params.user_id,
"foo.c" : req.params.user_id
}
},
{ safe: true },
function(e) {
...
}
);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1066 次 |
| 最近记录: |