node.js - Mongoose - findByIdAndUpdate - 不适用于 req.

我在通过 mongoose 更新 mongodb 中的文档时遇到问题。

我的模型如下:

var mongoose = require('mongoose');
var bcrypt = require('bcrypt-nodejs');

var UserSchema = new mongoose.Schema({
    first_name:{
        type: String
    },
    last_name:{
        type: String
    },
    email:{
        type: String,
        unique: true,
        required: true
    },
    password:{
        type: String,
        required: true
    },
    is_active:{
        type: Boolean,
        default: true
    },
    last_login:{
        type: Date
    }
});
module.exports = mongoose.model('User', UserSchema);

Controller 放函数如下:

exports.updateUser = function (req, res) {
    console.log(req.body);
    User.findByIdAndUpdate(req.body.user_id, {$set:req.body}, function(err, result){
        if(err){
            console.log(err);
        }
        console.log("RESULT: " + result);
    });
    res.send('Done')
}

控制台输出:

Listening on port 3000... { first_name: 'Michal', last_name: 'Test' } 
PUT /api/users/54724d0fccf520000073b9e3 200 58.280 ms - 4

打印的参数以表单数据(键值)的形式提供。看起来至少对我不起作用,知道这里有什么问题吗?

最佳答案

你必须使用 req.params.user_id 而不是 req.body.user_id

exports.updateUser = function (req, res) {   
    console.log(req.body);

    User.findByIdAndUpdate(req.params.user_id,{$set:req.body},{new:true}, function(err, result){
        if(err){
            console.log(err);
        }
        console.log("RESULT: " + result);
        res.send('Done')
    });
};

关于node.js - Mongoose - findByIdAndUpdate - 不适用于 req.body,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27108177/

相关文章:

java - Mongodb选择所有字段按一个字段分组并按另一个字段排序

python - Mongodb复制集自动重新连接在nginx + uwsgi上下运行后无法正常工作

mongodb - 在 mongo shell 中加载和运行聚合

mongodb - 使用聚合框架按子文档字段分组

node.js - NodeJS ExpressJS PassportJS - 仅用于管理页面

mongodb - Meteor.Collection 和 Meteor.Collection.Cu

mongodb - NoSQL 与关系数据库与可能的混合

java - MongoDB Java 驱动程序 : distinct with sort

ruby-on-rails - Mongoid 批量更新/Upsert 替代方案?

javascript - 在 MongoDB 更新语句中使用变量