Mongo将objectId返回为NULL

时间:2017-03-15 01:11:29

标签: node.js mongodb null objectid

快速问题: 当我在mongo中调用它们时,为什么我的id显示为Null。 当我在数据库中看到它们时,它们确实有一个id,但是当我通过应用程序调用它们时,它们显示为null。

控制台响应:

Mongoose:mpromise(mongoose的默认承诺库)已被弃用,请插入您自己的承诺库:http://mongoosejs.com/docs/promises.html

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

我的代码:

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

-----------我找到名字为bob的用户后,我会向用户附上帖子。 这是bobs用户架构

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

这些东西的ID已经存在..但是当我在应用程序中调用它们时,它们显示为null。 WHY !!! ???

0 个答案:

没有答案