M_W
M_W

Reputation: 66

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.

Upvotes: 0

Views: 839

Answers (2)

M_W
M_W

Reputation: 66

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");
  }
})

Upvotes: 1

Yunus TÜRE
Yunus TÜRE

Reputation: 46

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;
    }

Upvotes: 0

Related Questions