更新嵌套对象数组Mongoose Schema中的值

时间:2019-01-22 07:55:32

标签: node.js mongoose

我的架构设计如下

const templateSchema = new Schema({
  Main: {
    text: String,
    textKey: String,
    index: String,
    part: String,
    overallStatus: String,
    subjects: [
      {
        id: String,
        text: String,
        textKey: String,
        index: String,
        type: String,
        comment: String,
        image: String,
        answer: String,
}

我必须更新主题文本和主题ID,我这样做是

router.post("/edit", (req, res, next) => {
    Template.findOneAndUpdate({
        id: req.body.id,
        text: req.body.text
    }).then(updatedTemp => {
        console.log(updatedTemp);
        if (updatedTemp) {
            res.status(200).json({
                message: "Template updated.."
            });
        } else {
            res.status(404).json({
                message: "Checklist not found"
            });
        }
    });
});

它返回模板已更新且状态为200,但不会更新新值。如何在此架构中访问主题ID和主题文本

1 个答案:

答案 0 :(得分:0)

因此,根据提供的架构, 您应该在数组内部找到并在那里更新, 您可以执行以下操作:

router.post("/edit", (req, res, next) => {
  Template.update(
    {
      "Main.subjects.id": req.body.oldId,
      "Main.subjects.text": req.body.oldText,
      //you can pass some more conditions here
    },
    {
      $set: {
        "Main.subjects.$.id": req.body.id,
        "Main.subjects.$.text": req.body.text
      }
    }
  )
    .then(updated => {
      if (updated.nModified) {
        res.status(200).json({
          message: "Template updated.."
        });
      } else {
        //not updated i guess
      }
    })
    .catch(error => {
      //on error
    });
});

body中的有效载荷需要传递:

oldId : <which is currently there>,
oldText:  <which is currently there>,
id: <by which we will replace the id field>
text:<by which we will replace the txt>

注意: 假设idtext在所有文档中都是唯一的。

样本数据:

{
    "_id" : ObjectId("5be1728339b7984c8cd0e511"),
    "phases" : [ 
        {
            "phase" : "insp-of-install",
            "text" : "Inspection of installations",
            "textKey" : "",
            "index" : "1.0",
            "subjects" : [...]
        },...]
}

我们可以在此处[最顶层]更新text

Template.update({
"_id":"5be1728339b7984c8cd0e511",
"phases.phase":"insp-of-install",
"phases.text":"Inspection of installations"
},{
    "$set":{
        "phases.$.text":"Some new text you want to set"
    }
}).exec(...)

但是,如果您要进行深层嵌套更新, 您可以看看这个答案:@ nem035的here