简体   繁体   中英

Mongoose find subdocument in array and update it

Hi guys i have problem that i fail to solve. How can i find and update a singel subdocument in a array if i dont have the _id or do i need the _id? If i dont need the _id how can i find the subdocument in the array with example userId in this case and update the data fields.

const listSchema = new mongoose.Schema({
  userId: {
    type: String,
    require: true
  }, 
   data1: { type: String },
   data2: { type: String }
});

const testSchema = new mongoose.Schema({
orderId: {
    type: Number,
    require: true
  },
list: [listSchema]
});

module.exports = mongoose.model("Test", testSchema);

I have tryed something like this but i then get all the "list" obj and i cant find out how to get a singel "list" obj that have UserId: 1 lets say

try {
 await Test.findOne({ orderId: OrderId },"list");
} catch (err) {
...
}

Try this:

Test.findOne({ orderId: orderId, "list.userId": "1" })

More details here on how to query an array of sub-documents: Link

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