繁体   English   中英

添加不在模式中的字段 mongoose

[英]Add field not in schema with mongoose

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

创建我的 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);
        }
    });
};

然后调用它

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

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

您可以使用 option { strict: false }在架构中添加和删除字段

选项:严格

严格选项(默认情况下启用)确保传递给我们的模型构造函数的值不会在我们的架构中指定不会保存到数据库中。

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

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

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

您可以在此处查看文档

您可以使用 .add 在架构用户中添加新字段

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

谢谢。-

引用JonathanLonowski

ODM 旨在强制执行您定义的架构,验证每个属性是否属于并丢弃那些不属于的属性。

因此,为了使用mongoose更新字段,该字段必须存在于模型的架构中。

在创建模式时使用{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