简体   繁体   English

添加不在模式中的字段 mongoose

[英]Add field not in schema with mongoose

I am trying to add a new field to a document, but this isn't working:我正在尝试向文档添加新字段,但这不起作用:

Creating my UserModel prototype:创建我的 UserModel 原型:

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

Then calling it然后调用它

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.这会成功更新任何字段,只要它存在,但不会添加任何新字段。

You can add and remove fields in schema using option { strict: false }您可以使用 option { strict: false }在架构中添加和删除字段

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

You can check the documentations here您可以在此处查看文档

You can add new fields in schema User using .add您可以使用 .add 在架构用户中添加新字段

require('mongoose').model('User').schema.add({fullName: String});

Thanks.-谢谢。-

Quoting JonathanLonowski引用JonathanLonowski

The ODM is designed to enforce the schema you've defined, verifying that each property belongs and discarding those that don't. ODM 旨在强制执行您定义的架构,验证每个属性是否属于并丢弃那些不属于的属性。

So in order to update fields using mongoose the field must exist in the model's schema.因此,为了使用mongoose更新字段,该字段必须存在于模型的架构中。

use {strict:false} when you are creating schema在创建模式时使用{strict:false}

 const testschema = mongoose.Schema({ name: String, id: Number, isUsed: { type: Boolean, default: true }, },{strict:false})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM