我的架构如下
Sectionschema
var SectionSchema = new Schema({
name: String,
documents : {
type : [{
type: Schema.ObjectId,
ref: 'Document'
}]
}
}
}
DocumentSchema
var DocumentSchema = new Schema({
name: String,
extension: String,
access: String, //private,public
folderName : String,
bucketName : String,
desc: String
});
Api.js
exports.section = function(req, res, next, id) {
var fieldSelection = {
_id: 1,
name: 1,
documents : 1
};
var populateArray = [];
populateArray.push('documents');
Section.findOne({
_id: id
}, fieldSelection)
.populate(populateArray)
.exec(function(err, section) {
if (err) return next(err);
if (!section) return next(new Error('Failed to load Section ' + id));
// Found the section!! Set it in request context.
req.section = section;
next();
});
}
如果我走这条路,我有 'documents'对象是[]。但是,如果我删除,“populateArray.push('documents');”然后我得到文件:['5adfsadf525sdfsdfsdfssdfsd'] - 一些对象Id(至少)
请让我知道我需要填充的方式。
感谢。
答案 0 :(得分:1)
将您的查询更改为
Section.findOne({
_id: id
}, fieldSelection)
.populate('documents.type')
.exec(function(err, section) {
if (err) return next(err);
if (!section) return next(new Error('Failed to load Section ' + id));
// Found the section!! Set it in request context.
req.section = section;
next();
});
这是有效的。您需要提供填充路径。
答案 1 :(得分:0)
如果您只是想要"文件"在您的架构中指向稍后将填充的ObjectID数组。那么你可以用它。
var SectionSchema = new Schema({
name: String,
documents : [{
type: Schema.ObjectId,
ref: 'Document'
}]
});
并使用以下内容填充
Section.findOne({
_id: id
}, fieldSelection)
.populate('documents')
.exec(function(err, section) {
if (err) return next(err);
if (!section) return next(new Error('Failed to load Section ' + id));
// Found the section!! Set it in request context.
req.section = section;
next();
});