猫鼬人口密集

时间:2011-12-30 17:48:16

标签: node.js mongodb mongoose

这是我的测试代码,我无法弄清楚它为什么不起作用,因为它与测试'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

2 个答案:

答案 0 :(得分:2)

您的变量OwnedTagSchema必须在使用之前定义,否则您最终会基本上这样做:

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

将其移至MovieSchema定义之上。

答案 1 :(得分: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' }]
});