node.js - FindOneAndUpdate 与 mongoose 中的模型

标签 node.js mongodb express mongoose

我尝试了两种方法来覆盖不存在的现有文档。

第一种方式

此代码无效并在每次更新时抛出此错误:

error: *After applying the update to the document {_id: ObjectId('***') , ...}, the (immutable) field '_id' was found to have been altered to _id: ObjectId('***78')"*

exports.loginUser = function (req, res) {
var newUser = new userModel(req.body);
userModel.findOneAndUpdate({email: req.body.email}, newUser ,{ new: true, 

upsert:true, setDefaultsOnInsert: true }, function (err, userUpdate) {

return res.json(userUpdate);

}

第二种方式

直接插入请求 body 效果很好。但我不想那样做,因为 body 可能有垃圾:

exports.loginUser = function (req, res) {
var newUser = new userModel(req.body);
userModel.findOneAndUpdate({email: req.body.email}, req.body ,{ new: true, 

upsert:true, setDefaultsOnInsert: true }, function (err, userUpdate) {

return res.json(userUpdate);

}

所以有人可以建议我如何使用模型而不是请求主体执行 findOneAndUpdate

最佳答案

使用.update()方法:

var newUser = new userModel(req.body);

newUser.update(newUser, { upsert:true, setDefaultsOnInsert: true }, function (err) {
    if (err) {
        console.log(err);
        return res.json('Cannot save user');
    }

    res.json(newUser);
});

不需要使用 new:true 选项,因为 newUser 将始终包含更新或插入的文档

关于node.js - FindOneAndUpdate 与 mongoose 中的模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48626015/

相关文章:

node.js - 在请求之外检索本地和 heroku 应用程序主机名

node.js - 如何动态更改查询的值

r - Mongolite - 明显太大,16mb 上限

node.js - Mongoose:如何在填充期间排除虚拟 id 字段

mongodb - 使用 $unwind 时可以避免两次使用相同的 $match 标准吗?

node.js - react Node 通过 axios 传递文件,出现 multer 错误 500

node.js - MongoNetworkError : failed to connect to server [localhost:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 127. 0.0.1:27017]

node.js - 如何拒绝用户使用 mongoose-auth/everyauth 登录

javascript - 如何使用expressjs将数据从一个路由传递到另一个nodejs

Node.js 将对象转换为字符串并将字符串转换为对象?