mongoose填充

这是我的testing代码,我不知道为什么它不工作,因为它是非常类似于testing“一次填充子数组的多个孩子” 。

var mongoose = require('mongoose'), Schema = mongoose.Schema, ObjectId = Schema.ObjectId; mongoose.connect('mongodb://localhost/testy'); var UserSchema = new Schema({ name: String }); var MovieSchema = new Schema({ title: String, tags: [OwnedTagSchema] }); var TagSchema = new Schema({ name: String }); var OwnedTagSchema = new Schema({ _name: {type: Schema.ObjectId, ref: 'Tag'}, _owner: {type: Schema.ObjectId, ref: 'User'} }); var Tag = mongoose.model('Tag', TagSchema), User = mongoose.model('User', UserSchema), Movie = mongoose.model('Movie', MovieSchema); OwnedTag = mongoose.model('OwnedTag', OwnedTagSchema); User.create({name: 'Johnny'}, function(err, johnny) { Tag.create({name: 'drama'}, function(err, drama) { Movie.create({'title': 'Dracula', tags:[{_name: drama._id, _owner: johnny._id}]}, function(movie) { // runs fine without 'populate' Movie.find({}).populate('tags._owner').run(function(err, movies) { console.log(movies); }); }); }) }); 

产生的错误是

 node.js:201 throw e; // process.nextTick error, or 'error' event on first tick ^ TypeError: Cannot call method 'path' of undefined at /Users/tema/nok/node_modules/mongoose/lib/model.js:234:44 

更新

从OwnedTag中删除,并重写了这样的MovieSchema

 var MovieSchema = new Schema({ title: String, tags: [new Schema({ _name: {type: Schema.ObjectId, ref: 'Tag'}, _owner: {type: Schema.ObjectId, ref: 'User'} })] }); 

工作代码https://gist.github.com/1541219

您的variablesOwnedTagSchema必须在使用之前进行定义,否则您将最终完成此操作:

 var MovieSchema = new Schema({ title: String, tags: [undefined] }); 

将其MovieSchema定义之上。

我希望你的代码也能工作。 如果你把OwnedTag中的MovieSchema放在正确的MovieSchema ,它会起作用吗?

 var MovieSchema = new Schema({ title: String, tags: [{ _name: {type: Schema.ObjectId, ref: 'Tag'}, _owner: {type: Schema.ObjectId, ref: 'User'} }] }); 

编辑:

 var MovieSchema = new Schema({ title: String, tags: [{ type: Schema.ObjectId, ref: 'OwnedTag' }] });