javascript - Mongodb/ Mongoose : How to properly implement findOneAndUpdate on an express route

标签 javascript mongodb express mongoose

我想使用 findOneAndUpdate() 方法使用用户在 html 更新表单上输入的数据来更新现有模型(帐户)。 因此,如果用户决定仅更新电话号码字段,则仅更新电话号码字段,其余两个字段保持不变。

帐户架构:

    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);

这是我的路线代码:

    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');
    });

获取请求工作正常。我可以在获取请求上访问帐户模型,以向用户显示用户详细信息,但是更新路由没有执行任何操作。我知道我在更新后路线设置中遗漏了一些内容。 提前致谢。

最佳答案

编辑:我刚刚意识到您使用的findByIdAndUpdate错误。我的第一个答案仍然有效,并且可以在此之后找到。 findByIdAndUpdate 的第二个参数不是回调,而是包含要更改的值的对象。如果使用正确,您不必在请求结束时调用 .save()。 因此,更新架构的正确方法是:

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
});

原始答案: doc.save() 也接受回调,就像 findByIdAndUpdate 一样。因此,您必须在保存函数中嵌套另一个回调,然后您可以重定向。

这是我的做法(使用 promise ):

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);
    });
});

这是包含外部 promise 库的方法 - 我正在使用 'q' library :

// app.js
const mongoose = require('mongoose');
mongoose.Promise = require('q').Promise;

关于javascript - Mongodb/ Mongoose : How to properly implement findOneAndUpdate on an express route,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46447310/

相关文章:

Javascript 运行 "out of order"

javascript - 在嵌套 json 对象中按键查找并按值替换

javascript - polymer 嵌套 dom-repeat 模板乘以第二个模板

javascript - javascript中Object Array的值是如何操作的?

node.js - NodeJS 服务器上的 Mongoose 查询返回 NULL

javascript - 如何在前端显示响应数据?

node.js - 从同一个客户端取消之前的 MongoDB 操作

node.js - Node JS Express 样板和渲染

javascript - 原型(prototype) - 带有 id 的元素中带有 styleclass 的元素?

javascript - 是否可以将 SVG 对象的自定义属性设置为数字而不是字符串?