0

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?

Stennie
  • 63,885
  • 14
  • 149
  • 175
Mazzy
  • 13,354
  • 43
  • 126
  • 207

1 Answers1

1

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.

Comart
  • 64
  • 2
  • 8
  • The name of the schema has to be equal to the collection in mongodb? – Mazzy Aug 09 '14 at 20:50
  • 1
    Yes - instead of 'Brand' you would use the name of your table. I've found however that mongoose converts to lowercase and appends 's' to the end. For example if you wrote 'Brand' - the collection name might be 'brands'. This post discusses how to force a collection name: http://stackoverflow.com/questions/7486528/mongoose-force-collection-name – Comart Aug 09 '14 at 21:19