0

我的架构如下

部分模式

var SectionSchema = new Schema({
    name: String,
 documents : {
        type : [{
            type: Schema.ObjectId,
            ref: 'Document'
        }]
    }
}

}

文档架构

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();
    });
}

如果我这样做,我的“文档”对象是 []。但是,如果我删除,“populateArray.push('documents');” 然后我得到文件:['5adfsadf525sdfsdfsdfssdfsd'] -- 一些对象 ID(至少)

请让我知道我需要填充的方式。

谢谢。

4

2 回答 2

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();
    });

这有效。您需要提供填充路径。

于 2014-10-01T17:58:27.313 回答
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();
    });
于 2016-11-14T06:28:12.690 回答