問題描述
我使用 Mongoose.js,無法解決 3 級層次文檔的問題.
I use Mongoose.js and cannot solve problem with 3 level hierarchy document.
有兩種方法.
第一 - 沒有參考.
C = new Schema({
'title': String,
});
B = new Schema({
'title': String,
'c': [C]
});
A = new Schema({
'title': String,
'b': [B]
});
我需要顯示 C 記錄.我如何填充/找到它,只知道 C 的 _id?
I need to show C record. How can i populate / find it, knowing only _id of C?
我正在嘗試使用:
A.findOne({'b.c._id': req.params.c_id}, function(err, a){
console.log(a);
});
但我不知道如何從 returnet 中獲取我需要的僅 c 對象.
But i dont know how to get from returnet a object only c object that i need.
其次如果使用 refs:
C = new Schema({
'title': String,
});
B = new Schema({
'title': String,
'c': [{ type: Schema.Types.ObjectId, ref: 'C' }]
});
A = new Schema({
'title': String,
'b': [{ type: Schema.Types.ObjectId, ref: 'B' }]
});
如何填充所有 B、C 記錄以獲得層次結構?
How to populate all B, C records to get hierarchy?
我試圖使用這樣的東西:
I was try to use something like this:
A
.find({})
.populate('b')
.populate('b.c')
.exec(function(err, a){
a.forEach(function(single_a){
console.log('- ' + single_a.title);
single_a.b.forEach(function(single_b){
console.log('-- ' + single_b.title);
single_b.c.forEach(function(single_c){
console.log('--- ' + single_c.title);
});
});
});
});
但它會為 single_c.title 返回 undefined.我有辦法填充它嗎?
But it will return undefined for single_c.title. I there way to populate it?
謝謝.
推薦答案
在 Mongoose 4 中,您可以跨多個級別填充文檔:
In Mongoose 4 you can populate documents across multiple levels:
假設您有一個 User 架構來跟蹤用戶的朋友.
Say you have a User schema which keeps track of the user's friends.
var userSchema = new Schema({
name: String,
friends: [{ type: ObjectId, ref: 'User' }]
});
首先populate()
讓你得到一個用戶好友列表.但是,如果您還想要用戶的朋友的朋友怎么辦?在這種情況下,您可以指定 populate
選項來告訴 mongoose 填充所有用戶朋友的 friends
數組:
Firstly populate()
lets you get a list of user friends. But what if you also wanted a user's friends of friends? In that case, you can specify a populate
option to tell mongoose to populate the friends
array of all the user's friends:
User.
findOne({ name: 'Val' }).
populate({
path: 'friends',
// Get friends of friends - populate the 'friends' array for every friend
populate: { path: 'friends' }
});
取自:http://mongoosejs.com/docs/populate.html#deep-填充
這篇關于貓鼬填充嵌入式的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!