关于Mongoose Schema设计的问题

时间:2017-07-12 04:48:53

标签: node.js mongoose-schema

我对NoSQL世界完全陌生,我很难把它包裹起来。本周我用Node.js学习MongoDB(Mongoose),这是我目前的架构:

var eventDataSchema = new Schema({
  _id        : Number,
  notes      : {type: String, required: true},
  start_date : {type: Date, required: true},
  end_date   : {type: Date, required: true},
},  {
  id         : false,
  collection : 'event-data'
});
eventDataSchema.plugin(AutoIncrement);

var EventData = mongoose.model('EventData', eventDataSchema);

现在这个工作正常,我想添加一个用户和密码,并且可以访问EventData

另外......如果我想发送一个只有eventData的JSON,而不是用户发送给我的javascript,我该怎么办呢?

我目前以这种格式将eventData发送给我的js的方式:

router.get('/data', function(req, res){
  EventData.find({}, function(err, data){
    if (err) {
      console.error('Error occured');
    }
    res.send(data);
  });
});

再次感谢

1 个答案:

答案 0 :(得分:1)

我可以理解你想在你的架构中添加事件键。然后你的架构将是这样的:

    var userSchema = new Schema({
        user: { type: String, required: true, trim: true },
        password: { type: String, required: true, trim: true },
        events: [{ 
             notes: { type: String,required: true, trim: true },
             start_date: { type: Date,required: true },
             end_date: { type: Date,required: true } 
            }]
    }
    userSchema.plugin(AutoIncrement);
    var userSchema = mongoose.model('userSchema', userSchema);
 });

如果上述代码不起作用,那么您可以创建两个模式,一个用于用户,另一个用于eventData,并且可以在userSchema中填充eventData。

所以你的代码就是这样:

<强> userSchema.js:

var userSchema = new Schema({
        user: { type: String, required: true, trim: true },
        password: { type: String, required: true, trim: true },
        events: {type: mongoose.Schema.Types.ObjectId, ref: 'EventData' }

    userSchema.plugin(AutoIncrement);
    module.exports = mongoose.model('userSchema', userSchema);
});

您的 eventDataSchema 将是:

<强> eventSchema.js:

    var eventDataSchema = new Schema({
             notes: { type: 'string',required: true, trim: true },
             start_date: { type: Date,required: true },
             end_date: { type: Date,required: true } 
    }
    eventDataSchema.plugin(AutoIncrement);
    module.exports = mongoose.model('EventData', eventDataSchema);
 });

然后你可以得到这样的结果: index.js:

var eventSchema = require('./eventSchema');
var userSchema = require('./userSchema');

var populate = [{
        path: 'events',
        model: 'EventData',
        select: '_id notes start_dat end_date'
    }];

var find = function (query) {
    return userSchema.find(query).populate(populate).exec();
}
console.log(find());

<强>结果:

{
      _id:cfgvhbjnkmkdcfxghgjklxnmbxhdhjxjhjhgx,
      user: John Doe,
      password: 123,
      events: [ { _id: 1gfye56785g3ycgevhxeftx568765egcd,
                  notes: Event A,
                  start_date: 1/1/01, 
                  end_date: 1/1/01
                } ]

}