MongooseJS Pre保存钩具有参考值

时间:2015-01-28 16:26:40

标签: javascript node.js mongodb mongoose

我想知道是否可以在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。

如何完全填充此字段,以便在预保存挂钩中使用它?

由于

1 个答案:

答案 0 :(得分:3)

您需要再进行一次查询,但这并不是很难。人口只适用于查询,我不相信这种情况会有一个方便之处。

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