使用猫鼬添加不在模式中的字段 [英] Add field not in schema with mongoose

查看:29
本文介绍了使用猫鼬添加不在模式中的字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to add a new field to a document, but this isn't working:

创建我的 UserModel 原型:

Creating my 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);
                  ...
});

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

This successfully updates any field as long as it exists, but it won't add any new one.

推荐答案

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

选项:严格

strict 选项(默认启用)确保传递给的值我们的模式中未指定的模型构造函数没有得到保存到数据库中.

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

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

And also you can do this in update query as well

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

您可以在此处查看文档

这篇关于使用猫鼬添加不在模式中的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆