Marat Marat - 1 year ago 254
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


var mongoose = require('mongoose');

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


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)?'/api/stores', function(req, res) {
}, function(err, store) {
if (err)

Answer Source

You should use model reference and populate() method:

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'}); {

  store.itemsInStore.push(item); {
    // todo

Get items from a store

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

    // Stores with items
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download