Mazzy
Mazzy

Reputation: 14227

How should be the structure of a schema?

In my mongoDB there are stored several documents which have the same structure.

{
   "id": id1
   "brand": "name1"
   "models": [
       {
        "infos": {
           "foo1": "A"
           "foo2": "B"
       },
       }

     ]
}

I should get only brand values. Should I create the Schema {brand: String} or completely the exact schema as the document is saved on the db?

Upvotes: 0

Views: 46

Answers (1)

Comart
Comart

Reputation: 64

If all you ever will want is 'brand' then it suffices to only specify 'brand' in your schema. However this means that you can only ever read / or specify brand through your Mongoose model and none of the other fields.

For example:

>>>var schema = {brand: String};
>>>var MyModel = Mongoose.model('Brand', schema);
>>>
>>>var object = new MyModel({brand : 'test'})

the model will restrict you to only ever have the fields specified in the model:

>>>object.models = [];
>>>object.save();
>>>
>>>MyModel.findOne({}, function(err, result){
>>>  console.log(result.models);
>>>});
undefined 

Your model doesn't know about that field and has no way of handling it. It won't be able to save it to the database or retrieve it - even if you manage to put it there by other means. I recommend adding everything to your schema if at some point you may want to manipulate it.

Upvotes: 1

Related Questions