简体   繁体   中英

Mongoose populate

Here is my test code which I can not figure out why it isn't working, as it is very similar to test '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);
            });
        });
    })
});

Produced error is

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

Update

Got rid from OwnedTag and rewrote MovieSchema like this

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

Working code https://gist.github.com/1541219

Your variable OwnedTagSchema must be defined before you use it or you'll end up doing basically this:

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

Move it above MovieSchema definition.

I would expect your code to work, too. Does it work if you put the OwnedTag right in MovieSchema , like so?

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

edit:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM