Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to structure mongoose schema within a schema?

Tags:

mongoose

I'm new to mongodb and I have a data model like such

{
    last_updated: Date.now(),
    csgo_items:[
        {name: 'name', price: 1},
        {name: 'name', price: 1},
        {name: 'name', price: 1}
    ]
}

I have a 'last_updated' and then a giant list of csgo items I store.

My question is. Do I need two schemas? One for the two properties on the outer layer and one schema for my csgo item model?

How would my schemas look if I did it this way?

I have my item schema like such.

var ItemSchema = new Schema({
    price: Number,
    name: String,
});

Do I also need another schema to set for my outer schema like so?

var CsgoSchema = new Schema({
    last_updated: Date,
    item: Array,
});

Is this correct?

like image 570
Garuuk Avatar asked Apr 01 '16 04:04

Garuuk


1 Answers

Since you have defined your item schemas as

var ItemSchema = new Schema({
    price: Number,
    name: String
});

which has elements of the parent document items array, you can define the parent schema as

var CsgoSchema = new Schema({
    last_updated: Date,
    items: [ItemSchema]
});

When you want to add the items to the parent document array, you don't have to save each item individually first before adding it to the Csgo model, this is done whenever the top-level parent document is saved, for example

var Csgo = mongoose.model('Csgo', CsgoSchema);
var csgo = new Csgo({ 
    last_updated: new Date(),
    items: [
        {name: 'name1', price: 1},
        {name: 'name2', price: 2},
        {name: 'name3', price: 3}
    ] 
});

csgo.save(function (err) {
    if (err) return handleError(err)
    console.log('Success!');
});

You can also use MongooseArray methods such as push, unshift, addToSet to add the items to the parent document. For instance:

var Csgo = mongoose.model('Csgo', CsgoSchema);
var csgo = new Csgo;

// add an item using push
csgo.items.push({name: 'name4', price: 4});
var csgo_item = csgo.items[0];
console.log(csgo_item); // { _id: '56e2bc9f61fb33583128be07', name: 'name4', price: 4 }
csgo_item.isNew; // true

csgo.save(function (err) {
    if (err) return handleError(err)
    console.log('Success!');
});

You can also use the create method of MongooseArrays to add the items to the csgo document:.

var newcsgo = csgo.items.create({name: 'name', price: 1});
like image 57
chridam Avatar answered Sep 22 '22 20:09

chridam