2017-09-08 94 views
0

我有这样定义的猫鼬模型数组(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快速路由器:

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

根据猫鼬FAQ: 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(); 
+0

我试过了,但它对我无效。我找到了另一种方法:Bars.findOneAndUpdate({barid,date},{$ pull:{bookedby:username}})。添加ist只是$ push而不是$ pull。像魅力一样工作。我开始喜欢MongoDB。 – Michael