MongooseJS在预挂钩期间修改文档

use*_*145 2 mongoose mongodb node.js express compoundjs

我和猫鼬有一些问题.我的目标是在预保存期间,我将能够修改对象,如果需要可以分割标记,或者在另一种情况下计算子文档持续时间的总和并在主文档中更新它.

我发现如果我加载一个模型,然后调用doc.update传递新数据,只调用schema.pre('update', ...)触发器,并且this我的中间件内的任何更改都不会更新.我也尝试this.set('...', ....);在我的更新中间件中使用无济于事.

似乎我这样做doc.save(...),然后按预期附加到this内部的更改schema.pre('save', ...).除了将发布的变量扩展到我的模型的属性和保存之外,我没有看到任何方法来为此目的利用doc.update.

我的目标: - 通过以下方式更新现有文档doc.update(properties, ....) - 在保存期间使用中间件来修改文档,执行高级验证和更新相关文档 - 在更新期间使用中间件来修改文档,执行高级验证和更新相关文档 - 可互换使用模型. findByIdAndUpdate,model.save,model.findById-> doc.update,model.findById-> doc.save,并进入我的保存/更新中间件.

一些任意的示例代码:

function loadLocation(c) {
    var self = this;
    c.Location.findById(c.params.id, function(err, location) {
        c.respondTo(function(format) {
            if (err | !location) {
                format.json(function() {
                    c.send(err ? {
                        code: 500,
                        error: err
                    } : {
                        code: 404,
                        error: 'Location Not Found!'
                    });
                });
                format.html(function() {
                    c.redirect(c.path_to.admin_locations);
                });
            } else {
                self.location = location;
                c.next();
            }
        });
    });
}

LocationController.prototype.update = function update(c) {
    var location = this.location;
    this.title = 'Edit Location Details';

    location.update(c.body.Location, function(err) {
        c.respondTo(function(format) {
            format.json(function() {
                c.send(err ? {
                    code: 500,
                    error: location && location.errors || err
                } : {
                    code: 200,
                    location: location.toObject()
                });
            });
            format.html(function() {
                if (err) {
                    c.flash('error', JSON.stringify(err));
                } else {
                    c.flash('info', 'Location updated');
                }
                c.redirect(c.path_to.admin_location(location.id));
            });
        });
    });
};

module.exports = function(compound) {
    var schema = mongoose.Schema({
        name: String,
        address: String,
        tags: [{ type: String, index: true }],
        geo: {
            type: {
                type: String,
            default:
                "Point"
            },
            coordinates: [Number] // Longitude, Latitude
        }
    });
    schema.index({
        geo: '2dsphere'
    });
    var Location = mongoose.model('Location', schema);
    Location.modelName = 'Location';
    compound.models.Location = Location;

    schema.pre('save', function(next) {
        if(typeof this.tags === 'string') {
            this.tags = this.tags.split(',');
        }
    });
};
Run Code Online (Sandbox Code Playgroud)

==== *修改样本* ====

module.exports = function(compound) {
    var schema = mongoose.Schema({
        name: String,
        bio: String
    });

    schema.pre('save', function(next) {
        console.log('Saving...');
        this.bio = "Tristique sed magna tortor?"; 
        next();
    });

    schema.pre('update', function(next) {
        console.log('Updating...');
        this.bio = "Quis ac, aenean egestas?"; 
        next();
    });

    var Author = mongoose.model('Author', schema);
    Author.modelName = 'Author';
    compound.models.Location = Author;
};
Run Code Online (Sandbox Code Playgroud)

aar*_*ann 8

pre钩子适用于doc.save()doc.update().在这两种情况下都this指的是文档本身.

请注意,在编译模型之前,需要将钩子添加到模式中.

schema.pre('save', function(next) {
    if(typeof this.tags === 'string') {
        this.tags = this.tags.split(',');
    }
});
var Location = mongoose.model('Location', schema);
Run Code Online (Sandbox Code Playgroud)