簡體   English   中英

Mongodb / Mongoose:如何在快速路由上正確實現findOneAndUpdate

[英]Mongodb/Mongoose: How to properly implement findOneAndUpdate on an express route

我想使用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');
    });

獲取請求工作正常。 我可以在get請求中訪問帳戶模型,以向用戶顯示用戶詳細信息,但是更新路由沒有執行任何操作。 我知道我在路由更新設置后丟失了一些東西。 提前致謝。

編輯:我只是意識到您使用的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一樣。 因此,您必須在保存函數中嵌套另一個回調,然后可以在那里進行重定向。

這是我的做法(使用諾言):

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

這是您包括外部諾言庫的方法-我正在使用'q'庫

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM