我对NoSQL数据库有0次经验,很难不为这个问题提出“SQL解决方案”。我有一个餐厅,显然有一个地址。我的第一个想法是简单地放置很多字段,例如country,city,zip,line1等......但是我认为将它引用到Address文档,让我可以灵活地轻松更改地址的结构,所以之后我想出了一点研究:
var RestaurantSchema = new mongoose.Schema({
name: {
type: String,
required: true
},
address: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Address',
required: true
},
// a few more fields
createdAt: {type: Date, default: Date.now},
updatedAt: {type: Date, default: Date.now},
});
var AddressSchema = new mongoose.Schema({
restaurant: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Restaurant'
},
line1: {
type: String,
required: true
},
line2: {
type: String,
}
// etc
createdAt: {type: Date, default: Date.now},
updatedAt: {type: Date, default: Date.now},
});
我想知道如果我想从一个城市检索所有餐馆,我会怎么做,例如,我会做像find('Houston')这样的事情,然后从地址引用的每个id获取每个餐厅检索?
我觉得有更好的方法可以做到这一点,但此刻我甚至不知道还有什么可以搜索来寻找答案。
答案 0 :(得分:1)
您可以像这样制作地址架构
var AddressSchema = new mongoose.Schema({
restaurant: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Restaurant'
},
city: {
type: String,
required: true
},
line1: {
type: String,
}
// etc
createdAt: {type: Date, default: Date.now},
updatedAt: {type: Date, default: Date.now},
});
问:如果我想从一个城市取回所有餐馆,我会怎么做?
答:为此你可以使用moongose的填充
前:
var addressModule=require('addressSchema')
addressModule.find({city:'Houston'}).populate({'path':'restaurant','model':'restaurantSchema'})
结果:
[
{
restaurant:{
name:"ABC",
address:"123"
},
city:"Houston",
line1:"xxx"
},
{
restaurant:{
name:"DEF",
address:"233"
},
city:"Houston",
line1:"xxx"
}
]