一对多猫鼬 [英] Mongoose one-to-many

查看:73
本文介绍了一对多猫鼬的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您能解释一下如何组织猫鼬模型来创建一对多连接吗?需要保留单独的集合.

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

假设我有商店和物品

//store.js

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

我做对了吗?

以及如何访问传递给arryas的数据? 这是您输入商品名称的代码.但是如何输入id到id的数组(itemsinstore)?

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

推荐答案

您应该使用模型引用和populate()方法: http://mongoosejs.com/docs/populate.html

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

定义模型:

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

从商店获取物品

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

    // Stores with items
});

这篇关于一对多猫鼬的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆