【发布时间】:2016-08-01 12:04:02
【问题描述】:
我有一个应用程序,我正在尝试检查具有用户 ID 的文档是否已经存在,如果是,则使用请求中发送的数据更新现有文档,如果不存在则创建一个新文档。
到目前为止我已经这样做了:
Bio.findOne({userID: req.body.userID}, function(err, bio) {
if (err) {
console.log("The error while updating colleciton is " + err);
}
// if already exists then update it
if (bio) {
console.log("Bio document for user already exists!");
bio.userBios = {
$push: {
background: req.body.userBios.background,
experience: req.body.userBios.experience,
skills: req.body.userBios.skills,
bioForSector: req.body.userBios.bioForSector
}
}
bio.save(function(err) {
if (err)
throw err
return (null, bio)
})
}
//if does not exist then create new
if (!bio) {
console.log("Bio document for user does NOT exist! creating new");
var bio = new Bio();
bio.firstName = req.body.firstName;
bio.lastName = req.body.lastName;
bio.jobTitle = req.body.jobTitle;
bio.userID = req.body.userID;
bio.userBios = {
background: req.body.userBios.background,
experience: req.body.userBios.experience,
skills: req.body.userBios.skills,
bioForSector: req.body.userBios.bioForSector
};
// save the bio
bio.save(function(err) {
if (err)
throw err;
return (null, bio);
});
}
});
问题:
我可以成功创建一个新文档,但是当我尝试更新它时,它会覆盖整个 userBios 数组而不是更新它。
我的文档架构:
// define the schema for our bios model
var biosSchema = mongoose.Schema({
firstName: String,
lastName: String,
jobTitle: String,
userID: String,
userBios: [{bioForSector: String, background: String, skills: [String], experience: {}}]
});
我做错了什么?任何人都可以帮忙吗?将不胜感激!
【问题讨论】:
-
覆盖整个文档是什么意思?满足哪个条件?
-
@RayonDabre 当用户创建新文档时,它包含第一个简历的
background, skills, experience,但是当用户更新它而不是将新的background, skills, experience作为userBios数组中的新对象推送时在架构中,它会用所有空数据覆盖前一个架构。这意味着数据库中的background, skills, experience变量更改为null。这有帮助吗? -
@RayonDabre 我稍微改变了措辞,我的意思是它会覆盖整个
userbios数组,而不是通过将新对象推入其中来更新它。 -
只需将新项目推送到
bio.userBios:bio.userBios.push(userBiosObject)。并在bio.save()中使用回调或承诺 -
@AlexanderMac 感谢您的提示,成功了!!!
标签: javascript node.js mongodb mongoose