【问题标题】:Mongoose: updating a single sub-document issuesMongoose:更新单个子文档的问题
【发布时间】:2017-05-29 02:41:40
【问题描述】:

架构:

    var educationSchema = new Schema({
    schoolName: String,
    startDate: Number,
    endDate: Number,
    degree: String,
    major: String,
    grade: String
});

var UserSchema = new Schema({
  firstName: String,
  lastName: String,
  education: [educationSchema]
});

更新代码:

User.findOneAndUpdate(
  {"_id": req.user.id, "education._id": req.body.id},
  {
    "$set": {
        "education.$": req.body
    }
  }, 
  function(err, edu) {

  }
);    

现在,如果用户仅在 UI 上编辑 schoolName,则会发生以下情况:

保存前状态:

{
"_id" : ObjectId("5878fb4f51ec530358fea907"),
"firstName" : "John",
"lastName" : "Doe",
"education" : [
    {
        "schoolName" : "ABC",
        "startDate" : 1998,
        "endDate" : 2005,
        "degree" : "Bachelor’s Degree",
        "major" : "CS",
        "grade" : "3.5",
        "_id" : ObjectId("5878fbb951ec530358fea909")
    }
]

}

保存后状态:

"education" : [
    {
        "schoolName" : "XYZ"
    }
]

$set 不是合适的运算符吗?

【问题讨论】:

  • education.$ 引用子文档元素。所以更新字段的正确语法是"$set": { "education.$.schoolName": req.body },否则它将替换引用的元素,如您所见。

标签: node.js mongodb mongoose mongoose-schema


【解决方案1】:

更新education.$ 会更新子文档。如果您只想更新 schoolName,则必须使用 education.$.schoolName

将您的更新代码更改为:

User.findOneAndUpdate(
    {"_id": req.user.id, "education._id": req.body.id},
    {
        "$set": {
            "education.$.schoolName": req.body
        }
    }, 
    function(err, edu) {

    }
);  

编辑:更新通过 req.body 发送的任何字段

const update = {};

Object.getOwnPropertyNames(req.body).forEach(key => {
    update['education.$.' + key] = req.body[key];
});

User.findOneAndUpdate(
    {"_id": req.user.id, "education._id": req.body.id},
    {
        "$set": update
    }, 
    function(err, edu) {

    }
); 

【讨论】:

  • 我以schoolName为例,用户可以编辑/更改任何字段。如果他们更改了 schoolName 和 startYear 怎么办?
  • @kmansoor 我已经编辑了我的回复,以满足您更新通过请求正文进入的任何密钥的要求。
猜你喜欢
  • 2015-12-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-20
  • 1970-01-01
  • 2022-07-12
  • 2017-03-17
  • 2021-12-23
相关资源
最近更新 更多