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

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

问题描述

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

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选项(默认情况下启用)确保传递给我们的模型构造函数
的值没有在我们的模式中指定,不会将
保存到db。

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

您可以这里查看文件

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

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