javascript - 使用 Mongoose 添加不在模式中的字段

标签 javascript node.js mongodb mongoose mongodb-query

我正在尝试向文档添加新字段,但这不起作用:

创建我的 UserModel 原型(prototype):

model = require("../models/user")
UserModel.prototype.findOneAndUpdate = function(query, params, cb) {
    model.findOneAndUpdate(query, params, { returnNewDocument: true, new: true }, function(err, data) {
        if (!err) {
            cb(false, data);
        } else {
            cb(err, false);
        }
    });
};

然后调用它

userFunc = require("../../model_functions/user")

userFunc.findOneAndUpdate({
    "email.value": userEmail
}, {
    $set: {"wat":"tf"}
},
function (err, updatedUser) {
    //This logs the updated user just fine, but the new field is missing
        console.log(updatedUser);
                  ...
});

这会成功更新任何存在的字段,但不会添加任何新字段。

最佳答案

您可以使用选项 { strict: false }

在架构中添加和删除字段

选项:严格

The strict option, (enabled by default), ensures that values passed to our model constructor that were not specified in our schema do not get saved to the db.

var thingSchema = new Schema({..}, { strict: false });

您也可以在更新查询中执行此操作

Model.findOneAndUpdate(
  query,  //filter
  update, //data to update
  { //options
    returnNewDocument: true,
    new: true,
    strict: false
  }
)

您可以查看文档 here

关于javascript - 使用 Mongoose 添加不在模式中的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50934800/

相关文章:

javascript - 更新 ng 类上的特定对象

javascript - 在 Promise catch block 内解析

javascript - express js :separate controller and router file returns 404 error on route

mongodb - golang mgo 编码 bson

mongodb - Mongoose 是否只支持数组中的嵌入文档?

javascript - 按钮中的 URL 光标

javascript - 实时更新表单上的值

javascript - 如何解决获取json对象元素的问题

node.js - Meteor.js 在没有日志的情况下被杀死

mongodb - 无法连接到 MongoDB