Javascript MongooseJS使用Ref值预保存钩子
我想知道是否有可能在MongooseJS的预保存钩子中获得架构字段的填充ref值 我试图从ref字段中获取一个值,我需要ref字段(下面是用户字段),这样我就可以从中获取一个时区 模式:Javascript MongooseJS使用Ref值预保存钩子,javascript,node.js,mongodb,mongoose,Javascript,Node.js,Mongodb,Mongoose,我想知道是否有可能在MongooseJS的预保存钩子中获得架构字段的填充ref值 我试图从ref字段中获取一个值,我需要ref字段(下面是用户字段),这样我就可以从中获取一个时区 模式: var TopicSchema = new Schema({ name: { type: String, default: '', required: 'Please fill Topic name', trim: true },
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();
});
在上面的save钩子中,我试图访问this.user.timezone
,但该字段未定义,因为this.user
仅包含ObjectID
如何使此字段完全填充,以便在预保存挂钩中使用它
谢谢您需要进行另一个查询,但这并不难。Population只在查询中起作用,我不相信有一个方便的钩子用于这种情况
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();
});
});
成功了。然而,我确实需要做一些
var self=this代码>让东西工作的诡计。我还必须使用mogoose.model('User')
,而不是这里的User
类型,因为在运行时加载了类型。但这让我走上了正确的方向对不起,用户
位是假定的,当它不是我的代码时,总是忘记自我
!