猫鼬JS预保存钩子与引用值
MongooseJS Pre Save Hook with Ref Value
我想知道是否可以在 MongooseJS 的预保存钩子中获取架构字段的填充引用值?
我正在尝试从 ref 字段中获取一个值,我需要 ref 字段(下面,即用户字段),以便我可以从中获取时区。
图式:
var TopicSchema = new Schema({
name: {
type: String,
default: '',
required: 'Please fill Topic name',
trim: true
},
user: {
type: Schema.ObjectId,
ref: 'User'
},
nextNotificationDate: {
type: Date
},
timeOfDay: { // Time of day in seconds starting from 12:00:00 in UTC. 8pm UTC would be 72,000
type: Number,
default: 72000, // 8pm
required: 'Please fill in the reminder time'
}
});
预保存钩子:
/**
* Hook a pre save method to set the notifications
*/
TopicSchema.pre('save', function(next) {
var usersTime = moment().tz(this.user.timezone).hours(0).minutes(0).seconds(0).milliseconds(0); // Reset the time to midnight
var nextNotifyDate = usersTime.add(1, 'days').seconds(this.timeOfDay); // Add a day and set the reminder
this.nextNotificationDate = nextNotifyDate.utc();
next();
});
在上面的保存钩子中,我正在尝试访问this.user.timezone
但该字段未定义,因为this.user
只包含一个 ObjectID。
如何完全填充此字段,以便我可以在预保存钩子中使用它?
谢谢
您需要执行另一个查询,但这并不难。人口只适用于查询,我不相信这种情况有方便的钩子。
var User = mongoose.model('User');
TopicSchema.pre('save', function(next) {
var self = this;
User.findById( self.user, function (err, user) {
if (err) // Do something
var usersTime = moment().tz(user.timezone).hours(0).minutes(0).seconds(0).milliseconds(0); // Reset the time to midnight
var nextNotifyDate = usersTime.add(1, 'days').seconds(self.timeOfDay); // Add a day and set the reminder
self.nextNotificationDate = nextNotifyDate.utc();
next();
});
});
相关文章:
- Vanilla JS通过引用移除数组元素
- 无法获取属性'Id'使用Knockout.js的未定义或空引用API
- 引用vue.js中v-for中的上一个值
- 如何正确引用传递到淘汰中的当前元素的属性.JS
- 如何引用HTML中节点模块中的js文件
- 使用dc.js、d3.js和crossfilter引用错误
- 引用Ractive.js中的子属性
- Node.js引用错误:未定义类名
- 引用单个表的多列 - Sails JS API 模型
- 为什么firefox开发人员控制台引用script.js
- 如何在html中引用js脚本中的变量
- 引用JS文件所需的Javascript代码取决于Prod、Dev和stage环境
- 是否可以引用JS数组/对象中的另一个元素
- 如何正确引用js文件,以便外部html可以引用这些文件
- 从另一个属性引用js属性的正确方式
- 如何在倍数中获取引用js文件
- Jquery:引用js文件中的DOM准备函数
- 从Quickbase中的html文件中引用js文件
- 加载后引用JS和CSS文件
- 在JS文件中引用JS文件