2011-12-30 147 views
5

这是我的测试代码,我不知道它为什么不起作用,因为它与测试'populating multiple children of a sub-array at a time'非常相似。猫鼬填充

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

回答

1

我希望你的代码也能工作。如果你把OwnedTag的权利放在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' }] 
}); 
+0

不会,结果相同:-( – spacevillain 2011-12-30 18:48:28

+1

啊。其实,回到原来的模型。你使用的是'.populate',但是你使用的是'tags'的子文档,而不是ref。我没有期待它的工作 - 我们越来越远离NoSQL数据库的实力 - 但是,也许这将工作 - 看到上面的第二次尝试。 – danmactough 2011-12-30 19:26:24

+0

这打破了一切:-(我没有得到什么是https://github.com/LearnBoost/mongoose/blob/master/test/model.ref.test.js#L1109之间的区别也许你可以帮我看看吗? – spacevillain 2011-12-30 19:36:02

2

您的变量OwnedTagSchema你使用它,或者你会最终基本上是这样做之前,必须先定义:

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

移动它上面MovieSchema定义。