【问题标题】:MongooseJS Pre Save Hook with Ref ValueMongooseJS Pre Save Hook with Ref 值
【发布时间】:2015-03-27 15:42:14
【问题描述】:

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

我怎样才能让这个字段完全填充,以便我可以在预保存挂钩中使用它?

谢谢

【问题讨论】:

    标签: javascript node.js mongodb mongoose


    【解决方案1】:

    您需要进行另一个查询,但这并不难。人口仅适用于查询,我不相信这种情况有方便的钩子。

    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 类型。但这让我朝着正确的方向前进。 :)
    • 抱歉,User 位是假定的,当它不是我的代码时,总是忘记self
    猜你喜欢
    • 2021-01-08
    • 2013-08-15
    • 2014-03-22
    • 2022-10-23
    • 2019-09-10
    • 1970-01-01
    • 1970-01-01
    • 2016-04-29
    • 2015-07-20
    相关资源
    最近更新 更多