Mongoose - delete an element of an array of a subdocument

I have this little diagram for users:

{ username: String, contacts: Array } 

So, for example, some user contacts will look like this:

 { username: "user", contacts: [{'id': ObjectId('525.....etc'), 'approved': false}, {'id':ObjectId('534.....etc'), 'approved': true}] } 

Now I need to remove the item from the contacts, so I do:

 model.findByIdAndUpdate(23, {'$pull': { 'contacts':{'id':'525.....etc'} }}); 

but it seems that it does not work, no errors, but it is not deleted . I would just like to return this document to the user:

 { username: "user", contacts: [{'id':ObjectId('534.....etc'), 'approved': false}] } 

how to achieve this?

+6
source share
2 answers

The $pull operator actually fulfills the conditions for the array element on which it works. It seems that your question may not actually show that you are probably working with the ObjectId value that mongoose creates by default for all fields of the array.

Thus, you can make your request as follows after importing the ObjectId method:

 model.findByIdAndUpdate(23, { '$pull': { 'contacts':{ '_id': new ObjectId(someStringValue) } } }); 

Or, in fact, you can define your “circuit” a little better, and mongoose is actually an “autocast” ObjectId for you based on the “type” defined in the circuit:

 var contactSchema = new Schema({ approved: Boolean }); var userSchema = new Schema({ username: String, contacts: [contactSchema] }); 

This allows the mongoose to “follow the rules” for strongly typed field definitions. So, now it knows that you actually have a _id field for each element of the contacts array, and the "type" of this field is actually an ObjectId , so it will automatically throw the "String" set as a true ObjectId.

+10
source

finally!

 MongoDB: "imgs" : {"other" : [ { "crop" : "../uploads/584251f58148e3150fa5c1a7/photo_2016-11-09_21-38-55.jpg", "origin" : "../uploads/584251f58148e3150fa5c1a7/o-photo_2016-11-09_21-38-55.jpg", "_id" : ObjectId("58433bdcf75adf27cb1e8608") } ] }, router.get('/obj/:id', function(req, res) { var id = req.params.id; Model.findOne({'imgs.other._id': id}, function (err, result) { result.imgs.other.id(id).remove(); result.save(); }); 
+1
source

Source: https://habr.com/ru/post/976406/


All Articles