简体   繁体   中英

How to update the child document data in mongoose?

I need to update the value of tQuan to 15 where the tName is FBK in the stocks array. I couldn't find a correct answer yet. Please note that I'm not allowed to change the way that the schema is designed. Here's the schema.

const stockSchema = mongoose.Schema(
    {
        tName: {type: String},
        tQuan: {type: Number}
    }
)

const userSchema = mongoose.Schema(
  {
    name: {type: String},
    balance: {type: Number},
    stocks: [stockSchema]
  }
);

Here's how it looks on my mongoDB compass.

MongoDB Compass

I'm required to use mongoose in my backend with express, so this is not done in CLI. Please help me figure out the answer to this question, appreciate your help.

I found the answer. I'll post it here, in case if that helps someone else.

User.updateOne({ name: 'Sam' , "stocks.tName" : "FBK"},
{
  $set: {
    "stocks.$.tQuan": 15
  }
}, (err) => {
  if(err) {
    console.error(err);
  } else {
    console.log("successfully updated");
  }
})

If stockSchema is not stored in the database seperately, I can suggest, i mean if you just want to show stockSchema as:

user{
_id:"id",
name:"example",
balance:12345,
stoks:[
{
tName:"name",
tQuan:1234,
}
]
}

at Users Services or wherever you call save,update..etc functions:

 async function create(data) { const model = mongoose.model('User'); let arr=[] //tnamesArray from your form data.tnamesArray.forEach((name)=>{ let obj={} obj.tName=name arr.push(obj) }) //tQuansArray from your Form data.tQuansArray.forEach((quan,key)=>{ return arr[key].tQuan=quan; }) data.stocks=arr; const instance=new model(data); const savedInstance = await instance.save(); return savedInstance; }

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