我在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 router调用:
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优化空数组有关,但我该如何解决呢?
答案 0 :(得分:0)
根据猫鼬常见问题解答: 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();