Mongoose upsert 不创建默认架构属性 [英] Mongoose upsert does not create default schema property

查看:17
本文介绍了Mongoose upsert 不创建默认架构属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

示例文档架构:

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

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

I'm using a common request handler for edit and create of "Company" documents:

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 不使用默认值?

But using this method, when a new document is inserted, created, modified properties are not saved with default values of Date.now. Now I can call Company.create depending on the existence of an id but I'm wondering why upsert does not use default values if a property does not exist on a new document?

我使用的是猫鼬版本 ~3.8.10,

I'm using Mongoose version ~3.8.10,

推荐答案

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

What's going on is that none of Mongoose's validation, middleware, or default values are used when calling any of the "update" family of methods, like findByIdAndUpdate. They're only invoked by calls to save or create.

这样做的原因是更新"调用有效地传递到本机驱动程序,Mongoose 仅​​提供基于架构定义的字段类型转换.

The reason for this is that the "update" calls are effectively pass-throughs to the native driver, with Mongoose only providing type-casting of the fields based on the schema definition.

猫鼬 4.0 更新

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

Mongoose now supports setting defaults when a new document is created during an update, findOneAndUpdate, or findByIdAndUpdate upsert. Set the setDefaultsOnInsert option to true to enable this. This uses the $setOnInsert operator to create the defaults on insert.

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

这篇关于Mongoose upsert 不创建默认架构属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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