【问题标题】:Complex Relation in MongooseMongoose 中的复杂关系
【发布时间】:2014-10-25 23:53:48
【问题描述】:

我有一个餐厅创意,会有分店,每个分店都有一个菜单,每个菜单都有这个分店指定价格的项目!

我的架构是:

var mongoose = require('mongoose');

var eaterySchema = mongoose.Schema({
    name: String,
    type: Number,
    branches: [{type: Schema.Types.ObjectId, ref: 'Branch' }]
});

var branchSchema = mongoose.Schema({
    id: Number,
    name: String,
    eatery: {type: Schema.Types.ObjectId, ref: 'Eatery'},
    menu: {type: Schema.Types.ObjectId, ref: 'Menu'}
});

var menuSchema = mongoose.Schema({
    branch: {type: Schema.Types.ObjectId, ref: 'Branch'},
    items: [{type: Schema.Types.ObjectId, ref: 'Item'}]
});

var itemSchema = mongoose.Schema({
    name: String,
    description: String
});

var itemMenuSchema = mongoose.Schema({ //Many-To-Many Table
    menu: {type: Schema.Types.ObjectId, ref: 'Menu'},
    item: {type: Schema.Types.ObjectId, ref: 'Item'},
    price: Number
});


var Eatery = mongoose.model('Eatery', eaterySchema);
var Branch = mongoose.model('Branch', branchSchema);
var Menu = mongoose.model('Menu', menuSchema);
var Item = mongoose.model('Item', itemSchema);
var ItemMenu = mongoose.model('ItemMenu', itemMenuSchema);

下面的查询是否正确获取包含项目的菜单和请求的分支 id 的项目价格?

Branch
.findOne({id: '@GivenId'})
.populate('eatery menu')
.exec(function(err, doc){
        doc
        .populate('menu.items')
        .exec(function(err, doc){
            ItemMenu
            .find({})
            .where('menu._id').equals(doc.menu._id)
            .exec(function(err, items){
                doc.push(items);
                res.send(docs);
            })
        })
    };)
});

mongoose 是否提供填充来处理我在最后一个回调中编写的最后一个查询?以及处理这种复杂关系的更好解决方案是什么?

非常感谢

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    这个架构有点过于相关,并且查询会比它需要的慢得多。为了充分利用 MongoDB,我建议完全摆脱 ItemMenu:因为每个菜单都有一个项目列表,它是多余的,您可以将相应的价格存储在 Menu 的项目列表中。

    此外,您可以考虑将项目内联到每个菜单中,和/或将菜单内联到分支文档中。这将使您的查询更加简单和快捷。

    通常,在设计 MongoDB 架构时,您希望构建对象以便轻松回答最常见的问题。这通常意味着内联一对一或一对多的关系。不要陷入关系型思维模式——尝试像 SQL 行那样构建 MongoDB 文档是一种让你的生活变得更加困难的可靠方法:)

    【讨论】:

    • 非常感谢。我将其作为关系处理,因为编写 mongoose 是为了将 mongoDB 作为对象处理。您希望我如何为上面的示例构建架构?
    • 非常感谢,你拯救了我的一天:) 在得到你的答案之前这么说。并在此之后感谢数百人;)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-12
    • 1970-01-01
    相关资源
    最近更新 更多