Tuesday 14 March 2017

Mongo returns objectId as NULL

QUick QUESTION: Why are my ids showing as Null when I call them in mongo. They do have an id when i see them in the data base but when i call them through the app they show as null.

console response:

Mongoose: mpromise (mongoose's default promise library) is deprecated, plug in your own promise library instead: http://mongoosejs.com/docs/promises.html

    { _id: 58c76e48f339ce0d322f59a5,
      name: 'bob',
      email: 'bob@bob.com',
      __v: 3,
  posts: [ null, null, null ] }


My code:

  post.create({                                          //create a post with following data
      title:"working code",
    content:"Ive cracked this part"
},function(post)    {                                     //give that post a callback function
    mongoose.model("user").findOne({name:"bob"},function(err,foundUser){  //that finds one user model with name bob

        if(err){console.log(err)}

        else{                                                  //if found push in the post that was created
            foundUser.posts.push(post);
            foundUser.save(function(err,saved){               //and save bobs new details
            if(err)
            {console.log(err)}
            else
            {console.log(saved)}

        }) 
  }
  })
  })

mongoose.model("user").findOne({name:"bob"}).populate("posts").exec(function(err,user){
    if(err){console.log(err)}
else{console.log(user, user.posts.id)}});

-----------I attach a post to a user once i find a user with name bob.. Here is bobs user schema

var userSchema= new mongoose.Schema({
    name:String,
    email:String,
    posts:[{
        type:mongoose.Schema.Types.ObjectId,    //posts attribute looks for an id in a mongoose schema 
        ref:"post"                               // THe schema reference is post
            }]
});

THE IDS of these things DO EXIST.. but when I call them in the app they show as null.. WHY!!!???



via Chris Cullen

No comments:

Post a Comment