【问题标题】:Mongoose update update nested object inside an array猫鼬更新更新数组内的嵌套对象
【发布时间】:2021-09-22 22:31:58
【问题描述】:

我正在尝试查询和更新名册数组 (roster.schedule.monday.start) 中的一个元素,然后更新此示例中的值。

monday.start 这两个键需要是动态的

我认为方法是这样的

  1. 通过_id查找文档

  2. 通过_id在数组中查找匹配的对象

  3. 更新嵌套值

我在下面尝试了这个,但没有成功,有人可以帮助解决这个问题

非常感谢

// Mongoose query

exports.updateRoster = (req, res) => {

  const editDay = req.body.day;
  const value = req.body.valueOfEntry;
  const userId = req.body.id;
  const rosterId = req.body.rosterId;
  const startPerieod = req.body.time;


  let dynObj = {
    ["rosters.$.schedule.$." + editDay + ".$." + startPerieod]: value,
  };


  Carer.updateOne({ "rosters._id": rosterId }, { $set: dynObj }).exec(
    (err, roster) => {
      if (err) {
        return res.status(400).json({
          error: err,
        });
      }
      res.json(roster);
    }
  );
};


// Schema 

const mongoose = require("mongoose");
const { ObjectId } = mongoose.Schema;

const carersSchema = new mongoose.Schema({
 
  
  rosters: [
    {

   schedule: {

     monday: {

       start: { type: String },
       finish: { type: String },
       notes: { type: String },


    }, 
  ],

});

module.exports = mongoose.model("Carers", carersSchema);


【问题讨论】:

  • 如果您可以输入样本数据并输出样本数据(您想要的预期输出),则可以更快地获得答案

标签: javascript node.js mongodb mongoose


【解决方案1】:

尝试使用 link 中的 $set 和数组过滤器

Carer.findOneAndUpdate({_id: carerId}, 
{ 
  "$set": {[`rosters.$[outer].schedule.${editDay}.${startPerieod}`]: value} 
},
{ 
  "arrayFilters": [{ "outer._id": roasterId }]
},
function(err, response) {
  if(err) console.log(err)
  console.log(response)
})

【讨论】:

  • 这很有效,非常感谢,非常好的方法
猜你喜欢
  • 2014-07-13
  • 2020-09-06
  • 1970-01-01
  • 1970-01-01
  • 2013-11-24
  • 2018-09-11
  • 1970-01-01
  • 2020-03-01
  • 2020-10-06
相关资源
最近更新 更多