我目前正在使用貓鼬v4.10.8
,並試圖在定義的模型上填充多個數組。具有mongoose.populate返回空陣列
TransportModel.js
//Transport model
'use strict';
const mongoose = require('mongoose');
const TransportSchema = new mongoose.Schema({
tag: {
type: String,
enum: ['X', 'Y'],
required: true,
unique: true
},
chairs: [{
type: mongoose.Schema.Types.ObjectId,
ref: "Chair"
}],
targets: [{
type: mongoose.Schema.Types.ObjectId,
ref: "Target"
}]
});
module.exports = mongoose.model('Transport', TransportSchema);
ChairModel.js
//Chair model
'use strict';
const mongoose = require('mongoose');
const ChairSchema = new mongoose.Schema({
product_name: {
type: String,
required: true,
unique: true
},
description: {
type: String,
unique: false,
required: false
}
});
module.exports = mongoose.model('Chair', ChairSchema);
TargetModel.js
//Target model
'use strict';
const mongoose = require('mongoose');
const TargetSchema = new mongoose.Schema({
target_name: {
type: String,
required: true,
unique: true
},
location: {
type: String,
required: true,
unique: false
},
description: {
type: String,
unique: false,
required: false
}
});
module.exports = mongoose.model('Target', TargetSchema);
後以上配置到位後,我創建了一個Chair
文件和一個Target
文件。
之後,我調用下面的邏輯路徑上得到一個Transport
文件:
TransportModel.findOne({
tag: 'X'
})
.populate("chairs")
.populate("targets")
.exec(function(err, transport) {
if (err) {
console.error(err);
}
console.log('Transport: ', transport);
});
});
下面是檢索文件:
{
"_id": "xxxx9999xxxx9999xxxx9999",
"tag": "X",
"__v": 1,
"chairs": [],
"targets": []
}
因此,即使我質疑Chairs
和Targets
集合,我確實至少有1個文檔,Transport
文檔沒有得到填充。
此外,我也嘗試過的.populate()
的增強版本,但我不斷收到空數組:
.populate({
path: "chairs",
model: "Chair"
})
.populate({
path: "targets",
model: "Target"
})
你怎麼了'Chair'和'Target'文檔添加到'TransportModel'文件? – robertklep
感謝您的回覆,@robertklep。這就是我想用'.populate()'實現的目標,我希望'Transport'文件的'chairs'和'targets'數組自動填充整個可用的'Chair'和'Target'列表來自各自館藏的文件。 –
儘管這不是人口的問題。這是將各個集合中的_particular_文檔關聯起來的一種手段。換句話說,您必須手動將新的「Chair」文檔與「TransportModel」文檔相關聯。然後'.populate()'方法將在查詢期間自動添加關聯的文檔。請參閱文檔:http://mongoosejs.com/docs/populate.html – robertklep