Marat Marat - 19 days ago 6
Node.js Question

Mongoose one-to-many

can you explain me how to organize mongoose models to create one to many connections? It is needed keep separate collections.

suppose i have stores and items

//store.js

var mongoose = require('mongoose');

module.exports = mongoose.model('Store', {
name : String,
itemsinstore: [ String]
});


//item.js

var mongoose = require('mongoose');
module.exports = mongoose.model('Item', {
name : String,
storeforitem: [String]
});


Am i doing it in the right way?

And how to access pass data to arryas?
Here is the code yo enter name to item. But how to enter id to array of id's (itemsinstore)?

app.post('/api/stores', function(req, res) {
Store.create({
name: req.body.name,
}, function(err, store) {
if (err)
res.send(err);
});
})

Answer

You should use model reference and populate() method: http://mongoosejs.com/docs/populate.html

Define your models:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var storeSchema = Schema({
   name : String,
   itemsInStore: [{ type: Schema.Types.ObjectId, ref: 'Item' }]
});
var Store = mongoose.model('Store', storeSchema);

var itemSchema = Schema({
    name : String,
    storeForItem: [{ type: Schema.Types.ObjectId, ref: 'Store' }]
});
var Item = mongoose.model('Item', itemSchema);

Save a new item into an existing store:

var item = new Item({name: 'Foo'});
item.save(function(err) {

  store.itemsInStore.push(item);
  store.save(function(err) {
    // todo
  });
});

Get items from a store

Store
  .find({}) // all
  .populate('itemsInStore')
  .exec(function (err, stores) {
    if (err) return handleError(err);

    // Stores with items
});