猫鼬人口密集

spa*_*ain 5 mongoose mongodb node.js

这是我的测试代码,我无法弄清楚它为什么不起作用,因为它非常类似于测试'一次填充子数组的多个子元素'.

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);
            });
        });
    })
});
Run Code Online (Sandbox Code Playgroud)

产生的错误是

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
Run Code Online (Sandbox Code Playgroud)

更新

摆脱了OwnedTag并像这样改写了MovieSchema

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

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

dan*_*ugh 1

我希望你的代码也能工作。如果你像这样输入OwnedTag正确的值,它会起作用吗?MovieSchema

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

编辑:

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

  • 有机会时请输入解决方案作为解决方案 (3认同)