CSh*_*arp 7 mongoose node.js mongoose-schema
我在 mongoose 中有一个用户模型架构,其中包含一个朋友和群组列表以及stats像这样的信息......
var user = new Schema({
email: { type: String, required: true, unique: true },
password: { type: String, required: true, select: false },
roles: [{ type: String, required: true }],
friends: [{ type: Schema.Types.ObjectId, ref: 'User' }],
groups: [{ type: Schema.Types.ObjectId, ref: 'Group' }],
stats : {
nbrFriends: { type: Number, required: false },
nbrGroups: { type: Number, required: false }
}
}, {
timestamps: true
});
Run Code Online (Sandbox Code Playgroud)
stats每当对friends或groups字段进行更改以包含friends或groups等的新数量时,我都需要更新用户。例如,当对用户调用以下函数时:
var addGroup = function(user, group, cb) {
user.groups.push(group);
User.findOneAndUpdate({ _id: user._id }, { $set: { groups: user.groups }}, { new: true }, function(err, savedResult) {
if(err) {
return cb(err);
}
console.log('updated user: ' + JSON.stringify(savedResult));
return cb(null, savedResult);
});
};
Run Code Online (Sandbox Code Playgroud)
我如何确保stats自动更新以包含groups用户的新号码?中间件功能似乎是这里的最佳方法。我尝试了以下操作,但这似乎从未被调用...
user.pre('save', function(next) {
var newStats = {
nbrGroups: this.groups.length,
nbrPatients: this.friends.length
};
this.stats = newStats;
this.save(function(err, result) {
if(err) {
console.log('error saving: ' + err);
} else {
console.log('saved');
}
next();
});
});
Run Code Online (Sandbox Code Playgroud)
您需要使用中间件(又名挂钩):
中间件(也称为 pre 和 post hook)是在异步函数执行期间传递控制权的函数。
请参阅文档:
| 归档时间: |
|
| 查看次数: |
11475 次 |
| 最近记录: |