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

后端 未结 2 578
不思量自难忘°
不思量自难忘° 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: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.

提交回复
热议问题