Mongoose one-to-many

空扰寡人 提交于 2019-12-09 04:27:51

问题


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

回答1:


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



回答2:


You can do using the best practices with Virtuals.

Store.js

const mongoose = require('mongoose')
const Schema = mongoose.Schema

const StoreSchema = new Schema({
    name: {
        type: String,
        required: true
    },
    createdAt: {
        type: Date,
        default: Date.now
    }
})

StoreSchema.virtual('items', {
    ref: 'Item',
    localField: '_id',
    foreignField: 'storeId',
    justOne: false // set true for one-to-one relationship
})

module.exports = mongoose.model('Store', StoreSchema)

Item.js

const mongoose = require('mongoose')
const Schema = mongoose.Schema

const ItemSchema = new Schema({
    storeId: {
        type: Schema.Types.ObjectId,
        required: true
    },
    name: {
        type: String,
        required: true
    },
    createdAt: {
        type: Date,
        default: Date.now
    }
})

module.exports = mongoose.model('Item', ItemSchema)

StoreController.js

const Store = require('Store.js')

module.exports.getStore = (req, res) => {
    const query = Store.findById(req.params.id).populate('items')

    query.exec((err, store) => {
        return res.status(200).json({ store, items: store.items })
    })
}

Keep in mind that virtuals are not included in toJSON() output by default. If you want populate virtuals to show up when using functions that rely on JSON.stringify(), like Express' res.json() function, set the virtuals: true option on your schema's toJSON options.

// Set `virtuals: true` so `res.json()` works
const StoreSchema = new Schema({
    name: String
}, { toJSON: { virtuals: true } });



回答3:


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




回答4:


Try this:

 Store.findOne({_id:'5892b603986f7a419c1add07'})
  .exec (function(err, store){
    if(err) return res.send(err);

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

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


来源:https://stackoverflow.com/questions/35245685/mongoose-one-to-many

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!