Cast to ObjectId failed for value “586cc8b3ea780c071bbe2469” at path “_id” for model “User”

后端 未结 2 566
不思量自难忘°
不思量自难忘° 2021-01-20 13:14

I saw a couple of post with similar to mine but I still getting the same error

here is my user schema

相关标签:
2条回答
  • 2021-01-20 13:31

    I had the same problem with mongoose version > 4.7.2

    Problem is about bson package.

    I solved it with installing an older version of mongoose.

    npm install mongoose@4.7.2

    or you can change package.json to use exact version 4.7.2 "mongoose": "4.7.2"

    You can update to newer versions after the problem is solved. You can track it on here.

    0 讨论(0)
  • 2021-01-20 13:43

    The error exists in your serializeUser function in passport.

    You need to use user._id instead of user.id.

    since there is no field as id in your UserSchema, user.id will beundefined, and while deserializing the user, undefined is not typeOf ObjectId, thus it is throwing above error.

    Try this:

    passport.serializeUser(function(user, done) {
        done(null, user._id);
      });
    

    Update:

    Do this in your deserializeUser:

    cast the upcoming id to ObjectId, just to be sure, and then use that ID to query the User.

    var userId = mongoose.Schema.Types.ObjectId(id);
    User.findById(userId , function(err, user) {
       done(err, user);
    });
    

    Dont forget to include mongoose in the same file.

    var mongoose=require('mongoose');
    

    Hopefully this will help you.

    0 讨论(0)
提交回复
热议问题