简体   繁体   中英

Delete element from deeply nested array, express mongodb

My deeply nested array structure is like this:

user {
    "_id" : ObjectId("58d6aedc7b9785e422d89ab7"),
    "email" : "blah",
    "password" : "blah",
    "username" : "blah",
    "places" : [ {
         "_id" : ObjectId("58d85c63d6270650fa05a674"),
         "description" : "blah blah",
         "country" : "blah",
         "state" : "blah",
         "latitude" : "-23",
         "longitude" : "12",
         "name" : "blah blah",
         "photos" : [
             {
                 "name" : "blah",
                 "photo_url" : "vhttp://blahblah.com",
                 "_id" : ObjectId("58d85c7ad6270650fa05a675")
             },
             {
                 "name" : "blah",
                 "photo_url" : "blah blah",
                 "_id" : ObjectId("58d85cc9d6270650fa05a676")
            }
        ]
    }]
    "__v" : 0
}

Can anyone please help in writing a mongoose query to delete a specific photo object based on its id? I have tried the following query, but it is not working:

User.update(
    {'_id': req.params.userId},
    {'places._id': req.params.placesId },
    { $pull: { "photos" : { id: req.params.id } } },
false,
true
);

There are several problems with your query:

  1. You are trying to specify two conditions, but you have submitted them as separate parameters; you need to combine them into the first conditions parameter
  2. In your update parameter, you are specifying the key "photos"; but this key does not exist at the top level of the document. To act on a key which is nested, you need to use dot notation ; and to pick out a single matching document in an array, you need the $ positional operator
  3. As noted by Shumi Gupta, an _id field should be named accurately, with the leading underscore

To remedy these problems, your update query should look something like this:

User.update(
  {"_id": req.params.userId, "places._id": req.params.placesId },
  { $pull: { "places.$.photos" : { "_id": req.params.id } } },
  false,
  true
);

Note: your third and fourth parameters, the boolean values, do not seem to match the parameters required by the mongoose Update call ; however, I am not an expert with Mongoose and you may be using an older version in which that structure is correct.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM