Reputation: 7083
I am trying to create schema where body
can have different keys in it based on the incoming event. So when i try to rendered data it just send _id
to client event
is not part of results. Did i implemented wrong schema with for this approach ?
event.model.js
var mongoose = require('bluebird').promisifyAll(require('mongoose'));
var bmpEventSchema = new mongoose.Schema({
event: {
type: String,
body : {}
}
});
export default mongoose.model('BmpEvent', bmpEventSchema);
JsonDocument
{
"_id" : ObjectId("596f672f4c387baa25db5ec6"),
"event" : {
"type" : "json",
"body" : {
"evntType" : "Smtduki",
"tkt" : "75522655",
"cat" : "RNT",
"esc_lvl" : "4",
"asset" : "DNEC843027 ATI",
"esc_tm" : "2017-05-26 09:18:00",
"tos" : "T3APLS",
"mcn" : "SL6516",
"cusTkt" : "",
"tktSrc" : "BMP",
"tier1" : "STLMOETS"
}
}
}
Upvotes: 0
Views: 870
Reputation: 566
This is a use case for discrimnators. You can make body a Mixed type but that will defeat the purpose of mongoose to provide validation. Suppose you have are modeling a books' database. You make a key named Professor for an academic book. But then you need to make a key novelist for a novel. You need to store genre for novel but not for educational books. Now you can make a type key like you did in your use case and play with the results. But then you may have to apply default values for novelist in novels. Or you may need to set a field required in one of the types and not the other. Another problem with that approach would be to use middlewares (hooks) to the different types. You may want to perform a different function on creation of novel and a different function on creation of an educational book. It is just a scenario and you can have like 10 or 15 types which will be even more cumbersome to handle. Now in order to avoid these issues you can make a different model for each type. But if you do that, when you want to query all books, you will have to perform a query on each of the models which will be ineffecient. You need something on the ODM layer. This is where discriminators come into play. You make a base model with all the keys you want in all types of books and add a discrimnator key to it(refer to docs). Then you create novel from this model's discriminator function and add additional keys which will only be in novel. You can create as many child models as you like this way and then you can use them in simply a polymorphic manner. Internally, this will create a single collection named books but for novels it will store only novels' keys. The validation, middlewares etc of the different types of models will be handled by the ODM layer. http://mongoosejs.com/docs/discriminators.html
Upvotes: 0
Reputation: 3154
There are two approaches I can suggest:
Example:
"key": {
type: "string",
required: true
}
Upvotes: 0
Reputation: 37038
Schema is wrong. Should be:
var bmpEventSchema = new mongoose.Schema({
event: {
type: String,
body : Mixed
}
});
Upvotes: 0