【发布时间】:2015-08-01 13:56:31
【问题描述】:
我是否需要在 Mongoose 架构中列出派生属性?这是架构最佳做法吗?
我使用.post('init') 挂钩从保存的值中派生属性。例如,我连接 fname 和 lname 在 post init 钩子中间件中创建 fullName。
但是这个中间件不起作用:
ContactSchema = new new mongoose.Schema({
fname: String,
lname: String
});
ContactSchema.post('init',function(doc){
doc.fullName= 'fname` + ' ' + 'lname';
});
// ... declare model
ContactModel.findOne({_id: req.params.contactId}).then(function(result){
console.log(result);
// {fname: "John",
// lname: "Smith"}
//
// missing fullName!
});
除非我将架构更改为也列出 fullName,否则它可以工作,并且 fullName 属性设置在中间件内的 fineOne() 之后。
ContactSchema = new new mongoose.Schema({
fname: String,
lname: String,
fullName: String,
});
ContactSchema.post('init',function(doc){
doc.fullName= 'fname` + ' ' + 'lname';
});
// ... declare model
ContactModel.findOne({_id: req.params.contactId}).then(function(result){
console.log(result);
// {fname: "John",
// lname: "Smith",
// fullName: "John Smith"}
//
// now fullName is populated and middleware works!
});
我是否应该列出永远不会保存的属性,以便让我的中间件工作?这是最佳做法吗?
【问题讨论】:
标签: mongoose