我在Mongo中运行查询,以便我只能显示除帐户ID以外的所有子模式。但是,作为回调" list_data"的结果,我得到了未定义。这就是我的查询在我的路线中写的方式:
exports.list_data = function(req, res){
models.Director.find({})
.populate("full_name").populate("dob").populate("favorite_movies").populate("favorite_camera")
.exec(function(err, list_data){
res.render('users', {"dirs": list_data});
})
};
这是我的模特:
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/lvsAPI');
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
//set schema
var Schema = mongoose.Schema;
var directorSchema = new Schema ({
account_id: Number,
full_name: String,
dob: Date,
favorite_camera: String,
favorite_movies: String
});
var Director = mongoose.model("Director", directorSchema);
module.exports = {"Director": Director};
答案 0 :(得分:1)
这很简单没有结果。 并且您的架构使用populate()时出错了。 请参阅official docs并正确执行:
var mongoose = require('mongoose')
, Schema = mongoose.Schema
var personSchema = Schema({
_id : Number,
name : String,
age : Number,
stories : [{ type: Schema.Types.ObjectId, ref: 'Story' }]
});
var storySchema = Schema({
_creator : { type: Number, ref: 'Person' },
title : String,
fans : [{ type: Number, ref: 'Person' }]
});
var Story = mongoose.model('Story', storySchema);
var Person = mongoose.model('Person', personSchema);
ref 选项告诉Mongoose在填充期间使用哪个模型。 现在' ref'字段将填充:
Story
.findOne({ title: 'Once upon a timex.' })
.populate('_creator')
.exec(function (err, story) {
if (err) return handleError(err);
console.log('The creator is %s', story._creator.name);
// prints "The creator is Aaron"
})