为什么不能使用游标更新猫鼬模型?

时间:2018-10-08 21:03:23

标签: node.js mongodb mongoose

我正在使用comongoose从我的数据库中查询模型,如图in the Mongoose docs所示。但是,当我致电model.save()时,保存不会持久保存到数据库中。

co(function*() {
    const cursor = Model.find({
        isActive: true,

        $or: [
            // nextInvocation is not set
            { nextInvocation: null },

            // nextInvocation is in the past
            { nextInvocation: { $lt: + new Date() } },
        ],
    }).cursor();

    // iterate through model
    for (let model = yield cursor.next(); model != null; model = yield cursor.next()) {
        console.log(model);

        // update model.nextInvocation
        const interval = cronparser.parseExpression(model.cronString, {tz: model.timezone});
        model.nextInvocation = interval.next()._date.toDate();
        model.save(); // <<<<<<<<<<<<< WHY DOESN'T THIS WORK?

    ...
});

作为参考,我也使用cron-parser,尽管它没有给我带来任何问题。

console.log(model);的结果:

{ isActive: true,
  cronString: '0 10 * * 1-5',
  timezone: 'America/Denver',
  nextInvocation: 2018-10-08T20:42:32.615Z,
  _id: 5bbbc1421b60ff00159ccaf7,
  title: 'Better test',
  questions:
   [ { responses: [],
       _id: 5bbbc14d1b60ff00159ccaf8,
       text: 'some text number one',
       createdAt: 2018-10-08T20:42:53.598Z,
       updatedAt: 2018-10-08T20:42:53.598Z },
     { responses: [],
       _id: 5bbbc1571b60ff00159ccafa,
       text: 'some text number two',
       createdAt: 2018-10-08T20:43:03.673Z,
       updatedAt: 2018-10-08T20:43:03.673Z },
     { responses: [],
       _id: 5bbbc15d1b60ff00159ccafc,
       text: 'some text number three',
       createdAt: 2018-10-08T20:43:09.158Z,
       updatedAt: 2018-10-08T20:43:09.158Z } ],
  createdAt: 2018-10-08T20:42:42.835Z,
  updatedAt: 2018-10-08T20:43:09.158Z,
  __v: 3 }

我的模型如下:

const modelSchema = new Schema({
    title: {
        type: String,
        required: true,
    },

    isActive: {
        type: Boolean,
        default: true,
    },

    /**
     * cronString
     * A valid cron schedule string, such as `0 10 * * 1-5`
     */
    cronString: {
        type: String,
        required: true,
        default: '0 10 * * 1-5',
    },

    /**
     * timezone
     * The timezone which the cronString will apply to.
     */
    timezone: {
        type: String,
        required: true,
        default: 'America/Denver',
        enum: momentTz.tz.names(), // array of timezones from moment.js
    },

    questions: [questionSchema],

    /**
     * nextInvocation
     * The Date when the next call to this model will take place.
     */
    nextInvocation: {
        type: Date,
        default: + new Date(),
    },
}, { timestamps: true });

我的model.save()为什么不工作?

0 个答案:

没有答案