![](/img/trans.png)
[英]checked mongoose sava() data Create document if not exists, otherwise, update data
[英]Check if document already exists and if yes then update, otherwise create new - Mongoose
我有一个应用程序正在尝试检查是否存在具有用户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: {}}]
});
我究竟做错了什么? 有人可以帮忙吗? 将不胜感激!
就像亚历山大·麦克在评论中说的那样,您自己重写了数组。 如果文档存在,请尝试:
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)
});
}
这样,您就可以将其真正推入现有阵列中,而不用创建一个新阵列。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.