asedsami
asedsami

Reputation: 679

mongoose's documentation example for population, gives an error

i had this problem in my own code. i copied the code from the example at Mongoose Query Population to see what am i doing wrong. but i have the same problem with their code too. the problem is about the log in the exec callback:

console.log('The creator is %s', story._creator.name);
                                    ^

TypeError: Cannot read property '_creator' of null

and here is the code.

var mongoose = require('mongoose'),
    Schema = mongoose.Schema

var personSchema = Schema({
    _id     : Number,
    name    : String,
    age     : Number,
    stories : [{ type: Schema.Types.ObjectId, ref: 'Story' }]
});

var storySchema = Schema({
    _creator : { type: Number, ref: 'Person' },
    title    : String,
    fans     : [{ type: Number, ref: 'Person' }]
});

var Story  = mongoose.model('Story', storySchema);
var Person = mongoose.model('Person', personSchema);

now using the models, making a new Person and saving it. and also saving a story and making the _creator of it to be equal to the id of the Person model, called aaron

var aaron = new Person({ _id: 0, name: 'Aaron', age: 100 });

aaron.save(function (err) {
    if (err) return handleError(err);

    var story1 = new Story({
        title: "Once upon a timex.",
        _creator: aaron._id    // assign the _id from the person
    });

    story1.save(function (err) {
        if (err) return handleError(err);
        // thats it!
    });
});

Story
  .findOne({ title: 'Once upon a timex.' })
  .populate('_creator')
  .exec(function (err, story) {
       if (err) return handleError(err);
       console.log('The creator is %s', story._creator.name);
       // prints "The creator is Aaron"
});

UPDATE: in database i have only one collection called poeple with only one document:

{
    "_id": 0,
    "name": "Aaron",
    "age": 100,
    "stories": [],
    "__v": 0
}

the code does not have the world people in it so where the collection name comes from? i'm confused. thanks for any help you are able to provide.

Upvotes: 0

Views: 53

Answers (1)

zangw
zangw

Reputation: 48376

The story1 is saved until the callback function of it is called. Please try to move the Stroy.find into the callback function of story1.save as below.

story1.save(function (err) {
    if (err) return handleError(err);
    Story
      .findOne({ title: 'Once upon a timex.' })
      .populate('_creator')
      .exec(function (err, story) {
           if (err) return handleError(err);
           console.log('The creator is %s', story._creator.name);
           // prints "The creator is Aaron"
    });
});

Upvotes: 1

Related Questions