Mongoose:更新单个子文档问题

时间:2017-01-13 16:42:09

标签: node.js mongodb mongoose mongoose-schema

架构:

    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) {

  }
);    

现在,如果用户仅对schoolName上的UI进行了修改,则会发生以下情况:

预存状态:

{
"_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不适合使用吗?

1 个答案:

答案 0 :(得分:0)

更新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) {

    }
);