简体   繁体   English

猫鼬一对多

[英]Mongoose one-to-many

can you explain me how to organize mongoose models to create one to many connections? 你能解释一下如何组织mongoose模型来创建一对多的连接吗? It is needed keep separate collections. 需要保留单独的集合。

suppose i have stores and items 假设我有商店和商品

//store.js //store.js

var mongoose = require('mongoose');

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

//item.js //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? 以及如何访问传递数据到arryas? Here is the code yo enter name to item. 这是代码输入项目的名称。 But how to enter id to array of id's (itemsinstore)? 但是如何输入id到id的数组(itemsinstore)?

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

You should use model reference and populate() method: http://mongoosejs.com/docs/populate.html 您应该使用模型引用和populate()方法: 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
});

You can do using the best practices with Virtuals . 您可以使用Virtuals的最佳实践。

Store.js 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 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 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. 请记住,默认情况下,虚拟机不包含在toJSON()输出中。 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. 如果要在使用依赖于JSON.stringify()函数JSON.stringify()res.json() 函数 JSON.stringify()时显示填充虚拟,请在架构的toJSON选项上设置virtuals: true选项。

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

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. 在这两种情况下都要关注Item

And then you just want to pass the array of ObjectIDs in it. 然后你只想传递ObjectIDs数组。 See more here: http://mongoosejs.com/docs/populate.html 在此处查看更多信息: http//mongoosejs.com/docs/populate.html

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM