【问题标题】:how to update 2nd schema using node js (mongdb)如何使用节点 js (mongodb) 更新第二个模式
【发布时间】:2021-11-11 10:04:20
【问题描述】:

我正在尝试更新在第一个架构中引用的第二个架构

ownerSchema.js

var ownerSchema = Schema({
    fname     : String,
    lname     : String,
    shopPlace : { 
                  type: Schema.Types.ObjectId,
                  ref: 'Shop'
                }
});
var Owner = mongoose.model('Owner', ownerSchema);

shopSchema.js

var shopSchema = Schema({
    shopName  : String,
    location  : String,
    startDate : Date,
    endDate   : Date
});
var Shop  = mongoose.model('Shop', shopSchema);

所以我正在尝试像这样更新我的架构

const update = async (req, res) => {
  const { id } = req.params;
  let update = {};
  if (req.body.fname) update.fname = req.body.fname;
  if (req.body.lname) update.lname = req.body.lname;
  if (req.body.shopPlace.shopName) update.shopPlace.shopName = req.body.shopPlace.shopName;
  if (req.body.shopPlace.location) update.shopPlace.location = req.body.shopPlace.location;

   let newOwmer = new Owner.updateOne(
     { ownerId: id },
      {
        $set: update,
      },
      { runValidators: true }
     );
};

我正在尝试更新商店,但它无法正常工作,我不知道我错在哪里

【问题讨论】:

    标签: javascript node.js mongodb mongoose mongodb-query


    【解决方案1】:
      const update = async (req, res) => {
      const { id } = req.params;
      let update = {};
      let updateShop = {}
      if (req.body.fname) update.fname = req.body.fname;
      if (req.body.lname) update.lname = req.body.lname;
      if (req.body.shopPlace.shopName) updateShop.shopPlace.shopName = req.body.shopPlace.shopName;
      if (req.body.shopPlace.location) updateShop.shopPlace.location = req.body.shopPlace.location;
    
       // get shopPlace _id from Owner
       const { shopPlace } = await Owner.findOneAndUpdate(
         { _id: id },
          {
            $set: update,
          },
          { new:true}
         );
         // here you must have the document you just updated. Just recover the id of the shop to modify it in turn
    
        // update shop
        let newShop = await Shop.findOneAndUpdate(
         { _id: shopPlace },
          {
            $set: updateShop,
          },
          {new:true}
         );
    
    };
    

    【讨论】:

    • 不,它不工作:(
    • 我仍然无法更新我的 shopDetails
    • 您可能复制/粘贴了代码。尝试使其适应您的问题。已经开始通过 {_id: id} 更改 { ownerId: id }。我根据您发布的内容给出了答案,希望您能适应它。通常它应该工作。否则我做一个小修改
    猜你喜欢
    • 1970-01-01
    • 2020-02-06
    • 2019-09-15
    • 2018-07-04
    • 1970-01-01
    • 1970-01-01
    • 2021-11-11
    • 2015-09-10
    • 1970-01-01
    相关资源
    最近更新 更多