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

创建我的用户模型原型:

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 }在模式中添加和删除字段

option: strict

strict选项(默认情况下启用)确保将值传递给

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

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

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

你可以查阅here 份文件

Mongodb相关问答推荐

geoLocation或geoNear为坐标和半径使用let变量

MongoDB Aggregate-如何在条件中替换字符串中的变量

我无法将文档发送到我的MongoDB集合,因为它告诉我使文档无效

将子元素的数组值提取到 mongodb 中的单个数组中?

pymongo - ifnull 重新调整整个对象而不是特定字段

Mongodb 按数组元素聚合组

使用golang的MongoDB错误无法访问服务器

使用MongoDB作为我们的主数据库,我应该使用单独的图数据库来实现实体之间的关系吗?

node.js & express - 应用程序 struct 的全局模块和最佳实践

mongoose默认值等于其他值

使用模拟 MongoDB 服务器进行单元测试

MongoDB 中 cursor.count() 和 cursor.size() 之间的区别

Clojure 和 NoSQL 数据库

django 和 mongodb 是否使迁移成为过go ?

带有 jQ​​uery Ajax/JSON 前端的 MongoDB 或 CouchDB 中间件

如何在mongodb中删除数组的第n个元素

在 mongoDB 中展平嵌套的 JSON struct

Cannot connect to MongoDB errno:61

初创公司应该考虑哪些数据库系统?

'this' 在 Mongoose 预保存挂钩中未定义