Reputation: 15685
I am trying to update multiple fields in a single document using 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) {
...
}
);
foo.a
is updated as expected but user_id is not removed from foo.b
.
Is it possible to have multiple update condition in a single operation using Mongoose/MongoDB?
Upvotes: 2
Views: 1550
Reputation: 312129
You need to combine both $pull
terms into a single object as you can't have two fields with the same name:
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) {
...
}
);
Upvotes: 5