繁体   English   中英

Mongoose:更新单个子文档问题

[英]Mongoose: updating a single sub-document issues

架构:

    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.$更新子文档。 如果您只想更新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) {

    }
); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM