node.js - Mongoose upsert 不创建默认模式属性

标签 node.js mongodb mongoose

示例文档架构:

var CompanySchema = Schema({
    created: { type: Date, default: Date.now },
    modified: { type: Date, default: Date.now },
    address: { type: String, required:true },
    name: { type: String, required:true }
});

我正在使用通用请求处理程序来编辑和创建“公司”文档:

exports.upsert = function(req, res) {
    helper.sanitizeObject(req.body);
    var company = {
        name: req.body.name,
        address: req.body.address
    };
    var id = req.body.id || new mongoose.Types.ObjectId();
    var queryOptions = {
        upsert: true
    };
    Company.findByIdAndUpdate(id, company, queryOptions).exec(function(error, result) {
        if(!error) {
            helper.respondWithData(req, res, {
                data: result.toJSON()
            });
        } else {
            helper.respondWithError(req, res, helper.getORMError(error));
        }
    });
};

但是使用这种方法,当插入一个新文档时,createdmodified属性并没有保存为默认值Date.now .现在我可以根据 id 的存在调用 Company.create 但我想知道如果新文档上不存在属性,为什么 upsert 不使用默认值?

我正在使用 Mongoose 版本 ~3.8.10,

最佳答案

发生的情况是,在调用任何“更新”系列方法(如 findByIdAndUpdate)时,没有使用 Mongoose 的验证、中间件或默认值。它们仅通过调用 savecreate 来调用。

原因是“更新”调用实际上是对 native 驱动程序的传递,Mongoose 仅​​提供基于模式定义的字段类型转换。

Mongoose 4.0 更新

Mongoose 现在支持在 updatefindOneAndUpdatefindByIdAndUpdate upsert 期间创建新文档时设置默认值。将 setDefaultsOnInsert 选项设置为 true 以启用此功能。这使用 $setOnInsert 运算符在插入时创建默认值。

var queryOptions = {
    upsert: true,
    setDefaultsOnInsert: true
};
Company.findByIdAndUpdate(id, company, queryOptions).exec( ...

关于node.js - Mongoose upsert 不创建默认模式属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25755521/

相关文章:

mongodb - 查找所有具有公共(public)字段的文档 mongodb

node.js - 如何通过 MongoDB 中的键查询子文档的映射?

node.js - 如何使用 Node.js 在 MongoDB 中使用 cursor.forEach()?

node.js - 找不到全局类型 'Array'

c# - 在 C# 中建模 mongodb 子集合

javascript - 类型错误 : Cannot read property 'title' of null

node.js - Mongoose 虚拟不工作

javascript - 从 Node HTTP 请求中运行的算法需要更长的时间来运行

node.js - 如何阻止来自特定浏览器的流量到我的 docker Web 应用程序?

node.js - 崩溃后如何自动重启 Node 脚本 - 或启动该 Node 的 init.d 服务?