【问题标题】:Mongoose models' save() won't update empty arrayMongoose 模型的 save() 不会更新空数组
【发布时间】:2017-09-08 12:10:27
【问题描述】:

我在 Mongoose 模型中有一个数组 (bookedby),定义如下:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

    var BarSchema = new Schema({
      date: {
        type: Date,
        required: true
      },
      barid: {
        type: String,
        required: true
      },
      bookedby: {
        type: [String],
        required: true
      },
    });

    module.exports = mongoose.model('Bar', BarSchema);

我使用以下函数更新它,由 nodejs express 路由器调用:

const Bars = require("../../models/bars");
const { getToday } = require('../../utils');

module.exports = function(req, res) {
  const { barid } = req.body;
  const { username } = req.user;
  const date = getToday();

  if( !barid ) return res.json({ success: false, error: 'Please specify parameter \'barid\'.'})

  Bars.findOne({ barid, date }, function (err, bar) {
    if (err) return next(err);

    if (!bar || bar.bookedby.indexOf(username) === -1) return res.json({ error: `Bar is not booked yet.` });

    // Someone booked the bar
    const index = bar.bookedby.indexOf(username);
    bar.bookedby.splice(index, 1);
    bar.save(err => {
      if (err) res.json({ error: `Error saving booking.` });
      else res.json({ success: true });
    });
  });
};

一切正常,除非我从 bookedby 数组中删除最后一项。然后 save() 函数不会更新数据库。最后一项仍然存在。我想这与mongodb优化空数组有关,但是我该如何解决呢?

【问题讨论】:

    标签: arrays mongodb mongoose model save


    【解决方案1】:

    根据猫鼬常见问题解答: http://mongoosejs.com/docs/faq.html

    对于 >= 3.2.0 版本,您应该使用 array.set() 语法:

    doc.array.set(3, 'changed');
    doc.save();
    

    如果您运行的版本低于 3.2.0,则必须在保存前标记数组已修改:

    doc.array[3] = 'changed';
    doc.markModified('array');
    doc.save();
    

    【讨论】:

    • 我试过了,但它对我不起作用。我找到了另一种方法:Bars.findOneAndUpdate({ barid, date }, { $pull: { bookingby: username } })。并添加 ist 只是 $push 而不是 $pull。像魅力一样工作。我开始喜欢 MongoDB。
    猜你喜欢
    • 2020-12-17
    • 2016-02-05
    • 1970-01-01
    • 1970-01-01
    • 2014-10-27
    • 2014-08-28
    • 2020-12-12
    • 2015-11-22
    • 1970-01-01
    相关资源
    最近更新 更多