2017-10-17 191 views
0

当我需要从我的服务器获取数据时,我在服务器中碰到了一堵墙。 以下代表我的模式:节点js,mongodb填充填充的

Schema one:{ 
name: String 
} 
Schema two:{ 
code:String, 
name_id: refid: schema One 
} 
Schema three:{ 
phone:number 
code:[refid: Schema two] 
} 

如果我需要从架构三个数据,并从对象ID中保存的代码阵列我会用填入,我会得到通过对象ID引用的对象中的对象。 问题是可以填充填充的数据吗? 如果填入模式3 我会得到的物体,如:

{phone : 000911, 
code: :{code:String, 
name_id: refid: schema One} 
前面的例子中,我要填充名字ID在

,这可能吗?

+0

尝试使用$查找https://stackoverflow.com/questions/9621928/how-do-i-query-referenced- objects-in-mongodb/39476690#39476690 – sidgate

+0

Schema是三个_code_:refid:Schema是一个还是两个?你也使用猫鼬? – TGrif

+0

模式三的代码是从模式2引用的,是的,我正在使用猫鼬 – motchezz

回答

1

随着猫鼬,您可以填充点符号您的模式是这样的:

const One = new Schema({ 
    name: String 
}) 

const Two = new Schema({ 
    code: String, 
    name: { 
    type: Schema.ObjectId, 
    ref: 'One' 
    } 
}) 

const Three = new Schema({ 
    phone: number 
    code: [{ 
    type: Schema.ObjectId, 
    ref: 'Two' 
    }] 
}) 


Three.find((err, three) => { 
    if (err) console.log(err) 
    console.log(three) 
    // => { 
    //  phone : "the phone number from schema Three", 
    //  code: { 
    //  code: "the code from schema Two", 
    //  name: "the name from schema One" 
    //  } 
    // } 
}) 
.populate('code.name') 
+0

如果代码是一个ID数组呢? – motchezz

+0

,如果我需要另一个人群,我们假设一个零架构,并且我需要从三到二填充到零 – motchezz

+0

这也适用于一个数组。如果您需要添加第三个级别,只需添加另一个点属性。请参阅[填充](http://mongoosejs.com/docs/populate.html)。 – TGrif