Home Ask Login Register

Developers Planet

Your answer is one click away!

Marat February 2016

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('Todo', {
    name : String,
    itemsinstore: [ String]
});

//item.js

var mongoose = require('mongoose');
module.exports = mongoose.model('Todo', {
    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);
    });
})

Answers


www.eugenehp.tk February 2016

Okay, this is how you define a dependancy:

var mongoose = require('mongoose');

module.exports = mongoose.model('Todo', {
    name : String,
    itemsinstore: [{ type: Schema.Types.ObjectId, ref: 'Item' }]
});

And make sure you have different names:

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

Keep an eye on Item in both cases.

And then you just want to pass the array of ObjectIDs in it. See more here: http://mongoosejs.com/docs/populate.html


Festo February 2016

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

Post Status

Asked in February 2016
Viewed 3,765 times
Voted 14
Answered 2 times

Search




Leave an answer


Quote of the day: live life