检查文档是否已经存在,如果是,则进行更新,否则创建新的-猫鼬 [英] Check if document already exists and if yes then update, otherwise create new - Mongoose
问题描述
我有一个应用程序,试图检查是否存在具有用户ID的文档,如果存在,则使用请求中发送的数据更新现有文档(如果不存在),然后创建一个新文档.
I have app where I am trying to check whether a document with the users ID already exists, if yes then update the existing one with the data sent in the request if it does not exist then create a new document.
到目前为止,我已经这样做:
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
数组,而不是对其进行更新.
I can successfully create a new document but when I try to update it, it overwrites the whole userBios
array rather then updating it.
我的文档架构:
// 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: {}}]
});
我做错了什么?有人可以帮忙吗?会非常感激的!
What am I doing wrong? Can anyone help? it'll be much appreciated!
推荐答案
就像Alexander Mac在评论中说的那样,您自己重写了数组.如果该文档存在,请尝试:
Like Alexander Mac says in the comments, you are overriding the array yourself. If the document exists, try:
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)
});
}
通过这种方式,您可以将其真正推送到现有阵列中,而不是创建一个新阵列.
This way you really push it in an existing array instead of creating a new one.
这篇关于检查文档是否已经存在,如果是,则进行更新,否则创建新的-猫鼬的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!