Mongoose-创建文档(如果不存在) ,否则在任何情况下都创建更新-返回文档

我正在寻找一种方法来重构我的部分代码,使之更短更简单,但是我不太了解 Mongoose,也不知道如何继续。

我试图检查一个集合是否存在一个文档,如果它不存在,就创建它。如果它真的存在,我需要更新它。在这两种情况下,我都需要在事后访问文档的内容。

到目前为止,我所做的就是查询特定文档的集合,如果找不到,就创建一个新文档。如果找到了,我会更新它(目前使用日期作为虚拟数据)。从那里,我可以访问找到的文档从我最初的 find操作或新保存的文档和这个工作,但必须有一个更好的方式来完成我所追求的。

这是我的工作代码,没有分心的临时演员。

var query = Model.find({
/* query */
}).lean().limit(1);


// Find the document
query.exec(function(error, result) {
if (error) { throw error; }
// If the document doesn't exist
if (!result.length) {
// Create a new one
var model = new Model(); //use the defaults in the schema
model.save(function(error) {
if (error) { throw error; }
// do something with the document here
});
}
// If the document does exist
else {
// Update it
var query = { /* query */ },
update = {},
options = {};


Model.update(query, update, options, function(error) {
if (error) { throw error; }
// do the same something with the document here
// in this case, using result[0] from the topmost query
});
}
});

我已经研究了 findOneAndUpdate和其他相关的方法,但是我不确定它们是否适合我的用例,或者我是否理解如何正确地使用它们。有人能告诉我正确的方向吗?

(可能)相关问题:


剪辑

在我的搜索过程中,我并没有遇到这个问题,但是在回顾了这些问题的答案之后,我得出了这个结论。在我看来,它当然更漂亮,而且很有效,所以除非我做了什么可怕的错事,否则我想我的问题可能就到此为止了。

如果您能对我的解决方案提供更多的意见,我将不胜感激。

// Setup stuff
var query = { /* query */ },
update = { expire: new Date() },
options = { upsert: true };


// Find the document
Model.findOneAndUpdate(query, update, options, function(error, result) {
if (!error) {
// If the document doesn't exist
if (!result) {
// Create it
result = new Model();
}
// Save the document
result.save(function(error) {
if (!error) {
// Do something with the document
} else {
throw error;
}
});
}
});
129161 次浏览

You are looking for the new option parameter. The new option returns the newly created document(if a new document is created). Use it like this:

var query = {},
update = { expire: new Date() },
options = { upsert: true, new: true, setDefaultsOnInsert: true };


// Find the document
Model.findOneAndUpdate(query, update, options, function(error, result) {
if (error) return;


// do something with the document
});

Since upsert creates a document if not finds a document, you don't need to create another one manually.

Since you wish to refactor parts of your code to be shorter and simpler,

  1. Use async / await
  2. Use .findOneAndUpdate() as suggested in this answer

let query = { /* query */ };
let update = {expire: new Date()};
let options = {upsert: true, new: true, setDefaultsOnInsert: true};
let model = await Model.findOneAndUpdate(query, update, options);
///This is simple example explaining findByIDAndUpdate from my code added with try catch block to catch errors
try{
const options = {
upsert: true,
new: true,
setDefaultsOnInsert: true
};
const query = {
$set: {
description: req.body.description,
title: req.body.title
}
};
const survey = await Survey.findByIdAndUpdate(
req.params.id,
query,
options
).populate("questions");
}catch(e){
console.log(e)
}

Here's an example:

const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/rsvp', {useNewUrlParser: true, useUnifiedTopology: true});


const db = mongoose.connection;


db.on('error', () => {
console.log('mongoose connection error');
});


db.once('open', () => {
console.log('mongoose connected successfully');
});


const rsvpSchema = mongoose.Schema({
firstName: String,
lastName: String,
email: String,
guests: Number
});


const Rsvp = mongoose.model('Rsvp', rsvpSchema);




// This is the part you will need... In this example, if first and last name match, update email and guest number. Otherwise, create a new document. The key is to learn to put "upsert" as the "options" for the argument.
const findRsvpAndUpdate = (result, callback) => {


Rsvp.findOneAndUpdate({firstName: result.firstName, lastName: result.lastName}, result, { upsert: true }, (err, results) => {
if (err) {
callback(err);
} else {
callback(null, results);
}
})
};




// From your server index.js file, call this...
app.post('/rsvps', (req, res) => {
findRsvpAndUpdate(req.body, (error, result) => {
if (error) {
res.status(500).send(error);
} else {
res.status(200).send(result);
}
})
});

Here is an example I am using. I have to return custom responses for UI updates etc. This can be even shorter. User is

const UserScheme = mongoose.Schema({
_id: String,
name: String,
city: String,
address: String,
},{timestamps: true});


const User = mongoose.model('Users', UserScheme);




async function userUpdateAdd(data){
var resp = '{"status": "error"}';
if(data){
var resp = await User.updateOne({ _id: data._id }, data).then(function(err, res){
console.log("database.userUpdateAdd -> Update data saved in database!");
if(err){
var errMessage = err.matchedCount == 0 ? "User Record does not exist, will create new..." : "Record not updated";
// If no match, create new
if(err.matchedCount == 0){
const create_user = new User(data);
resp = create_user.save().then(function(){
console.log("database.userUpdateAdd -> Data saved to database!");
return '{"status":"success", "message": "New User added successfully"}';
});
return resp;
}


// Exists, return success update message
if(err.matchedCount == 1){
return '{"status": "success", "message" : "Update saved successfully"}';
} else {
return '{"status": "error", "code": "' + err.modifiedCount + '", "message": "' + errMessage + '"}';
}
}
})
.catch((error) => {
//When there are errors We handle them here
console.log("database.userUpdateAdd -> Error, data not saved! Server error");
return '{"status": "error", "code": "400", "message": "Server error!"}';
});
}
return resp;
}