有关Mongoose Schemadevise的问题

对于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个人访问。

另外…后来,如果我想只发送一个JSON的eventData,而不是用户到我的JavaScript,我该怎么做?

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

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

再次感谢

       

网上收集的解决方案 "有关Mongoose Schemadevise的问题"

正如我可以理解你想在你的模式中添加事件键。 那么你的模式将是这样的:

  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); }); 

如果上面的代码不工作,那么你可以创build两个模式,一个用于用户,另一个用于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 } ] }