[英]Mongoose : filter then update document if it exists , otherwise create it
In the following method , i'm trying to search for a document using an email adress i provide. 在以下方法中,我试图使用我提供的电子邮件地址来搜索文档。 If the document exists i want to update the _id field, otherwise i create a totally new document . 如果文档存在,我想更新_id字段,否则我将创建一个全新的文档。
function (accessToken, refreshToken, profile, done) {
var newUser = new User();
newUser.name = profile.displayName;
newUser.email = profile.emails[0].value.toString();
options = { upsert: true, new: true, setDefaultsOnInsert: true };
update = { '_id': newUser._id };
User.findOneAndUpdate({ 'email': profile.emails[0].value.toString() }, update, options, function (err, user) {
newUser.save(function (err) {
if (err)
throw err;
newUser.token = newUser.generateJwt();
});
});
return done(null, newUser);
}
i get the following error in the console : 我在控制台中收到以下错误:
events.js:183 throw er; events.js:183 throw er; // Unhandled 'error' event ^ BulkWriteError: E11000 duplicate key error index: databasename.users.$ id dup key //未处理的“错误”事件^ BulkWriteError:E11000重复键错误索引:databasename.users。$ id dup键
Thank you for your help ! 谢谢您的帮助 !
You can try this using upsert : true
. 您可以尝试使用upsert : true
。 This will create the document if not found 如果找不到,这将创建文档
User.findOneAndUpdate(query, update, options, function(error, result) {
if (error) return;
// do something with the document
});
ps. ps。 You don't need to do newUser.save(..)
. 您不需要做newUser.save(..)
。 That'll do that for you if not found. 如果找不到,那将为您完成。 But I don't know why are you trying to update the id
as this would cause fatal consequences 但是我不知道您为什么要尝试更新id
因为这会导致致命的后果
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.