【发布时间】:2013-08-15 19:12:00
【问题描述】:
我遇到了一些关于猫鼬的问题。我的目标是,在预保存期间,我将能够修改对象,如果需要,可以进行拆分标签等操作,或者在另一种情况下计算子文档持续时间的总和并在主文档中更新它。
我发现如果我加载一个模型,然后调用 doc.update 传递新数据,只有schema.pre('update', ...) 触发器,并且我的中间件中对this 的任何更改都不会更新。我还尝试在我的更新中间件中使用this.set('...', ....);,但无济于事。
如果我改为使用doc.save(...),那么schema.pre('save', ...) 内对this 的更改会按预期附加。除了将发布的变量扩展到我的模型的属性和保存之外,我没有看到任何利用 doc.update 来实现此目的的方法。
我的目标:
- 通过doc.update(properties, ....) 更新现有文档
- 保存时使用中间件修改文档,做高级验证,更新相关文档
- 更新时使用中间件修改文档,做高级验证,更新相关文档
- 可互换使用 model.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(',');
}
});
};
==== * 修改样本 * ====
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;
};
【问题讨论】:
标签: node.js mongodb express mongoose compoundjs