简体   繁体   中英

how to query and update a nested array objects using Mongoose in Node js using the object id of the object in the nested array

I have a million questions cause I have thought of a million possible ways to do this. so I know using mongoose and mongodb the object id of a document will never be the same but is it possible that an object id will be reused by when and array in a document assigns object Id's to the objects in nested arrays.

I ask because I am trying to query and update using mongoose an array of objects now I noticed that each object in the nested array has its on object Id and I thought I could just find by id and update using that but then I was wonder are those unique to the whole database or just to that document?

then I thought I could write a query that has two parameters the documents obj id and the nested array object that has an obj id then update the name or address. the reason I was trying to use both id's is because names can be the same addresses can be the same, even cities can the same in this document or the other documents in the database I figured this 2 obj id's would be unique

lastly I wasn't sure if I should be using the $push to update the address of the object because i was wonder if there is an address there already will it delete the address or add to it in some way? I wasn't sure so I tried $set

here is my data

changeAdress: function(req, res) {

db.postData      
.findOneAndUpdate({ _id: req.params.id, people:{$eleMatch:{_id: req.body.person_Id}} },  {$set: {people: req.body.address}},{new:true})
  .then(dbModel => res.json(dbModel))
  .catch(err => res.status(422).json(err));

},

"_id" : ObjectId("5f09f40864d7219d546ff9e2"),

"state" : "New Jersey ",

"dateCreated" : ISODate("2020-07-11T17:16:56.898Z"),
"people" : [ 
    {
        
        "_id" : ObjectId("5fb99d00006799751407f843"),
        "address" : "789 main street ",
        "name" : "Roger wilco",
        "city" : "trenton",
        "dateCreated" : ISODate("2020-11-21T23:04:32.753Z")
    }
],
"__v" : 0

}

I tried this and it worked it doesn't find the document but it lets me update and since the array since I know the the the _id's

.update({ _id:req.params.id, "comments._id":req.body.commentId},  {$set: {"comments.$.comment": req.body.comment}},{new:true})

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