mongoose findByIdAndUpdate而不是save

时间:2016-12-08 18:53:36

标签: node.js mongodb mongoose

我正在尝试更新文档数组中元素的值。

通过save进行更新的常用方法可以正常工作,但尝试使用static方法(如findByIdAndUpdate)无法正常工作。

下面我粘贴我正在使用的代码:

var UserSchema = new mongoose.Schema({
  nickname: { type: String, trim: true},
  username: { type: String, trim: true },
  notifications: [{
    a: {
      _id: { type: mongoose.Schema.Types.ObjectId, ref: 'x' },
      x: { type: mongoose.Schema.Types.ObjectId, ref: 'y' }
    },
    b: {
      _id: { type: mongoose.Schema.Types.ObjectId, ref: 'y' },
      x: { type: mongoose.Schema.Types.ObjectId, ref: 'y' }
    },
    read: { type: Number, default: 0 }, // 0 - Unread, 1 - read
    ts: { type: Date, default: Date.now }
  }]
}, { timestamps: { createdAt: 'created_at' } });

// This works as expected
UserSchema.statics.rNSave = function (user_id, notification_id) {
  var vm = this;
  return new Promise(function (resolve, reject) {
    vm.findById(user_id, function (err, data) {
      if (err) {
        reject(new Error(err));
      } else {
        var notifications = data.notifications, i = 0;
        for (i; i < notifications.length; i += 1) {
          if (data.notifications[i]._id.toString() === notification_id) {
            data.notifications[i].read = 1;
            data.save({ validateBeforeSave: false }, function (err, updatedData) {
              if (err) {
                reject(new Error(err));
              } else {
                resolve();
              }
            });
            return;
          }
        }
        return reject('Error');
      }
    });
  });
};

// This one is not working
UserSchema.statics.rNStatic = function (user_id, notification_id) {
  return this.findByIdAndUpdate({ _id: user_id, notifications: { $elemMatch: { _id: notification_id }}}, { $set: { 'notifications.$.read': 1 }}).exec();
};

对此有何帮助?

感谢您的建议。

0 个答案:

没有答案