更新对象数组(Mongoose Schema) - Node.js.

时间:2017-02-19 19:29:06

标签: node.js mongodb mongoose-schema

这是我的房间架构room.js

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var config = require('../../config.js');

module.exports = mongoose.model(config.DATA_TYPE.ROOM, new Schema({
    name: String,
    guide: String,
    leader: String,
    partecipants_counter : { type: Number, default: 0},
    event_counter : { type: Number, default: 0},
    creation: { type: Date, default: Date.now},
    partecipants: [],
    events: [{ type: Schema.Types.ObjectId, ref: config.DATA_TYPE.EVENT}]
}));

这是我的事件架构event.js

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var config = require('../../config.js');

module.exports = mongoose.model(config.DATA_TYPE.EVENT, new Schema({
    id: Number,
    data: String,
    user: String,
    post: { type: Date, default: Date.now}
}, { _id: false }));

这两个模式位于/app/models/文件夹中,而我的经理脚本位于/app/managers/文件夹中。我的经理包含以下代码:

...
var Room = require('../models/room.js');
var Event = require('../models/event.js');
...
    createRoom: function(name,leader,guide,callback){
        new Room({
            name: name,
            guide: guide,
            leader: leader,
            partecipants : [guide,leader],
            partecipants_counter : 2
        }).save(callback);
    },
...
    pushEvent(roomId,eventData,sign,callback){
        this.getRoomById(roomId,function(err,data){
            if(sign == data.leader || sign == data.guide ){
                var new_event = {
                    id: data.event_counter,
                    data: eventData,
                    user: sign
                }

                Room.update(
                    { "_id" : roomId},
                    { $inc  : { event_counter : +1 },
                      $push : { events:
                                    { id : new_event.id,
                                      data : new_event.data,
                                      user : new_event.user
                                    }
                              } 
                    },function(err,data){
                            callback(err,new_event);
                    });
            }else{
                err = 1;
                callback(err);
            }
        });

    },
...

new_event已正确创建但我的update-query不起作用,一切都按预期运行,但我的数据库没有收到任何更新:我无法创建任何事件。

0 个答案:

没有答案