如何获取mongoose所有嵌套的文档对象

我是mongo DB的新手。 我正在开发一个使用MEAN堆栈的应用程序。 在我的后端,我有两个模型 – function和项目。

项目模式有一个叫做“特征”的属性,它是一个特征对象的数组。

var mongoose = require('mongoose'), Schema = mongoose.Schema; var ProjectSchema = new Schema({ name: { type: String, default: '', trim: true }, features:{ type: [Schema.ObjectId], ref: 'Feature' } }); /** * Statics */ ProjectSchema.statics.load = function(id, cb) { this.findOne({ _id: id }) .populate('features') .exec(cb); }; mongoose.model('Project', ProjectSchema); 

请注意,我有function和项目模式的单独文件。 我将这两个模式注册为mongoose模型。 我也有一个控制器,以及出口以下中间件function的项目:

 'use strict'; /** * Module dependencies. */ var mongoose = require('mongoose'), Project = mongoose.model('Project'), Testcase = mongoose.model('Feature'), _ = require('lodash'); /** * Find project by id */ exports.project = function(req, res, next, id) { Project.load(id, function(err, project) { if (err) return next(err); if (!project) return next(new Error('Failed to load project ' + id)); console.log(project.features.length); req.project = project; next(); }); }; 

因为我在项目模式的静态加载函数中使用了“.populate('features')”,所以我期待上面的项目对象中的Feature对象的所有细节。 但是它没有发生,它返回一个空数组的特性属性。 谁能告诉我我在这里错过了什么?

项目模式有一个叫做“特征”的属性,它是一个特征对象的数组。

小心那里。 你需要的是一个对应于Feature文档的ObjectIds数组。

我想你需要像这样指定project.features模式:

 features: [{type: Schema.ObjectId, ref: 'Feature'}] 

填充函数只有在代码和数据都是100%正确的情况下才有效,而且很容易出错。 你能发表你正在加载的项目文件的样本数据吗? 我们需要确保features确实是一个数组,真正包含ObjectIds而不是string或对象等。