【发布时间】: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