Search code examples
javascriptmongodbmongoosemongoose-populatedatabase

Collection isn't being saved in mongodb (Story collection from the mongoose populate documentation)


The below code gives me this error:

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

  TypeError: Cannot read property '_creator' of null

var express = require("express");
var app = express();
var mongoose = require("mongoose");
var Schema = mongoose.Schema;

mongoose.connect("mongodb://localhost/pop2");


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);


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
    });

    story1.save(function(err){
        if(err) return handleError(err);
        console.log("saved") //doe snot output saved
    })
})

Story.findOne({title : "Once upon a timex."})
        .populate("_creator")
        .exec(function(err, story){
            console.log(story)// I get an output of null in console could be from this
            if(err) return handleError(err);
            console.log("The creator is %s", story._creator.name)}) // error from above



app.listen(3000, function(){
    console.log("listening on 3000")
})

I'm just trying to follow the populate docs. so I want a solution that goes with that demo. I can't find what im missing.

When I do show collections I only see people and system.indexes collection not stories collection

EDIT :: I put the following inside the aaron.save() in the else part and I got an error

{ [MongoError: insertDocument :: caused by :: 11000 E11000 duplicate key error index: pop2.people.$_id_ dup key: { : 0 }]name: 'MongoError', message: 'insertDocument :: caused by :: 11000 E11000 duplicate key error index

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

            })

I figured that since it said "duplicate" I should drop the database and start the server again and I got the document. so that was good. But I tried to restart the server to save it again and I got a duplicate error again. now I need to drop the collections again. Why am I getting this duplicate error. If I just re-save normal docs I don't get this error.


Solution

  • I think this would do the trick.

    var express = require("express");
    var app = express();
    var mongoose = require("mongoose");
    var Schema = mongoose.Schema;
    
    mongoose.connect("mongodb://localhost/pop2");
    
    
    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);
    
    
    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
    });
    
    story1.save(function(err){
        if(err) return handleError(err);
        console.log("saved")
    });
    
    Story.findOne({title : "Once upon a timex."})
            .populate("_creator")
            .exec(function(err, story){
                console.log(story);
                if(err) return handleError(err);
                console.log("The creator is %s", story._creator.name)})
    
    
    
    app.listen(3000, function(){
        console.log("listening on 3000")
    });
    

    Just check it out and see if it works.