Node.js Mongoose .update With Arrayfilters
As it stands, I am able to get this functionality working using the Mongo shell, but having issues with the nested arrays inside of Node.js using Mongoose. Mongo shell command that
Solution 1:
I don't know if Mongoose 5.0.0 is supposed to support Arrayfilters out of the box but you can achieve it by using Mongoose's command-method which directly executes on MongoDB, hence can utilize all features available which includes ArrayFilters on MongoDB 3.6.1
Example:
mongoose.connection.db.command({update:<YourModel>.collection.name,updates: [
{
q: { 'field1.field2._id':mongoose.Types.ObjectId(<someObjectid>) },
u: {
$set: { 'field1.$.field2.$[field].fieldToUpdate':"updated!" },
},
arrayFilters: [
{ 'field._id':mongoose.Types.ObjectId(<someObjectid>) },
],
},
],})
Solution 2:
I tried it using the mongoose v5.0.14 and it works fine with MongoDB 3.6.3 version!
This is my package.json...
"dependencies":{"mongoose":"^5.0.14",}
This is my update function with arrayFilters...
...
// my id variable
letid = "5ad1f4dec48d7e156034c156";
// mongo condition
let mc = {_id: id};
// mongo dataset
let ds = {'contacts.$[i].main': false};
// mongo options
let op = {
arrayFilters: [
{
$and: [
{'i._id': {$ne: id}},
{'i.type': 'mobile'},
],
}],
};
<<Model>>.findOneAndUpdate(mc, ds, op, (err, doc) => {
callback(err, doc);
});
...
Post a Comment for "Node.js Mongoose .update With Arrayfilters"