[英]Mongodb/Mongoose: How to properly implement findOneAndUpdate on an express route
I want to use the findOneAndUpdate() method to update update an existing model(Account) with the data the user enters on a html update form. 我想使用findOneAndUpdate()方法使用用户在html更新表单上输入的数据来更新更新现有模型(帐户)。 So if the user only decides to update the phone number field, only the phone number field is updated and the two remaining fields stays the same. 因此,如果用户仅决定更新电话号码字段,则仅更新电话号码字段,其余两个字段保持不变。
The Account schema: 帐户架构:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var accountSchema = new Schema({
// Reference to the user model in session.
user: {type: Schema.Types.ObjectId, ref: 'User'},
// User's account information displayed on user's home page
first_name : {type: String},
last_name : {type: String},
phone_number: {type: String}
},
{timestamps: { createdAt: 'created_at', updatedAt: 'updated_at' }}
);
module.exports = mongoose.model('Account', accountSchema);
Here is the code for my route: 这是我的路线的代码:
app.get('/support', isLoggedIn, function (req, res, next) {
var account = Account({user: req.user});
Account.findOne({user: req.user}, function(err, account) {
if (err) {
res.send(500);
return;
}
console.log(account.first_name)
res.render('support', {user: req.user, account: account});
});
});
app.post('/support', isLoggedIn, function(req, res, next) {
var id = req.params.account._id;
Account.findByIdAndUpdate(id, function(err, doc) {
if (err) {
console.error('error, no entry found');
}
doc.first_name = req.body.first_name || doc.first_name;
doc.last_name = req.body.last_name || doc.last_name;
doc.phone_number = req.body.phone_number || doc.phone_number;
doc.save();
})
res.redirect('/home');
});
The get request works fine. 获取请求工作正常。 I can access the account model on the get request for displaying user details to the user but, the update route is not doing anything. 我可以在get请求中访问帐户模型,以向用户显示用户详细信息,但是更新路由没有执行任何操作。 I know I am missing something on the update post route setup. 我知道我在路由更新设置后丢失了一些东西。 Thanks in advance. 提前致谢。
EDIT: I just realized that you're using findByIdAndUpdate
wrong. 编辑:我只是意识到您使用的findByIdAndUpdate
错误。 My first answer is still valid though and can be found after this. 我的第一个答案仍然有效,但是可以在此之后找到。 findByIdAndUpdate
s second argument isn't a callback but an object containing the values to be changed. findByIdAndUpdate
的第二个参数不是回调,而是包含要更改的值的对象。 When used correctly, you do not have to call .save()
at the end of the request. 如果使用正确,则不必在请求结束时调用.save()
。 So, the correct way to update the schema would be this: 因此,更新架构的正确方法是:
Account.findByIdAndUpdate(req.params.account._id, {
$set:{
first_name: req.body.first_name,
// etc
}
}, {new: true}, function(err, updatedDoc){
// do stuff with the updated doc
});
ORIGINAL ANSWER: the doc.save()
also takes a callback, just as findByIdAndUpdate
does. 原始答案: doc.save()
也接受回调,就像findByIdAndUpdate
一样。 So you have to nest another callback inside your save function, and there you can then redirect. 因此,您必须在保存函数中嵌套另一个回调,然后可以在那里进行重定向。
Here's how I'd do it (using promises): 这是我的做法(使用诺言):
app.post('/support', function(req, res, next){
Account.findOne({_id: req.params.account._id}).exec()
.then(function(doc){
doc.first_name = req.body.first_name || doc.first_name;
// etc ...
return doc.save();
})
.then(function(){
// Save successful! Now redirect
res.redirect('/home');
})
.catch(function(err){
// There was an error either finding the document or saving it.
console.log(err);
});
});
And here's how you include an external promise library - I'm using the 'q' library : 这是您包括外部诺言库的方法-我正在使用'q'库 :
// app.js
const mongoose = require('mongoose');
mongoose.Promise = require('q').Promise;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.