MongooseJS Pre保存钩与Ref值

我想知道是否有可能在MongooseJS的预存储钩子中得到一个Schema字段的填充ref值?

我试图从ref字段中获取一个值,并且需要ref字段(下面是User字段),以便我可以从中获取时区。

架构:

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(); }); });