简体   繁体   English

如何更新mongoose中的子文档数据?

[英]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.我需要将tQuan的值更新为15 ,其中tName股票数组中的FBK 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 指南针上的外观。

MongoDB Compass MongoDB 罗盘

I'm required to use mongoose in my backend with express, so this is not done in CLI.我需要在我的后端使用 mongoose 和 express,所以这不是在 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:如果 stockSchema 没有单独存储在数据库中,我可以建议,我的意思是,如果您只想将 stockSchema 显示为:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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