NodeJs在方法findById上mongoose CastError

时间:2016-10-26 11:55:22

标签: node.js mongodb mongoose

我遇到了mongoose的问题,当我使用方法findById时,我收到错误:  CastError: Cast to ObjectId failed for value "protected" at path "_id"

我的_id由mongoose.Types.ObjectId.isValid(_id);

进行有效测试

我还测试过将我的字符串_id转换为ObjectId:mongoose.Types.ObjectId(_id)同样的错误......

我的模特是:

var UserSchema = new Schema({
  _id: {type:ObjectIdSchema, default: function () { return new ObjectId()} },
  email: { type: String, unique: true, required: true },
  pseudonyme: { type: String, unique: true, required: true },
  password: { type: String, required: true }})

我使用node v6.7.0和mongoose v4.6.5

事先请求帮助,

完整代码:

const jwtLogin = new JwtStrategy(jwtOptions, function(payload, done) {  
  //payload { _id: "58109f58e1bc7e3f28751cdb",email: "antoine.drian@laposte.net",exp: 1477494763,firstName: "antoine",iat: 1477484683,lastName: "drian"}
  var isValid = mongoose.Types.ObjectId.isValid(payload._id);
  if(!isValid) done(null, false);

  var ObjectId = mongoose.Types.ObjectId;


  var _id = ObjectId(payload._id);

  User.findById( _id , function(err, user) {
    if (err) { return done(err, false); }

    if (user) {
      done(null, user);
    } else {
      done(null, false);
    }
  });
});

模型/ user.js的

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var ObjectIdSchema = Schema.ObjectId;
var ObjectId = mongoose.Types.ObjectId;

var bcrypt = require('bcrypt');

// set up a mongoose model
var UserSchema = new Schema({
   // _id: {type: Schema.Types.ObjectId, auto: true},
    email: { type: String, unique: true, required: true },
    pseudonyme: { type: String, unique: true, required: true },
    password: { type: String, required: true },
    profile: {
        firstName: { type: String, required: true },
        lastName: { type: String, required: true },
        birthdate: { type: Date },
        gender: { type: String, enum: ['Male', 'Female'] },
    }
}, {
    timestamps: true
});

UserSchema.pre('save', function(next) {
    var user = this;
    if (this.isModified('password') || this.isNew) {
        bcrypt.genSalt(10, function(err, salt) {
            if (err) {
                return next(err);
            }
            bcrypt.hash(user.password, salt, function(err, hash) {
                if (err) {
                    return next(err);
                }
                user.password = hash;
                next();
            });
        });
    } else {
        return next();
    }
});

UserSchema.methods.comparePassword = function(passw, cb) {
    bcrypt.compare(passw, this.password, function(err, isMatch) {
        if (err) {
            return cb(err);
        }
        cb(null, isMatch);
    });
};

module.exports = mongoose.model('User', UserSchema);

3 个答案:

答案 0 :(得分:0)

首先不要在你的架构中定义 _id ,然后更改'isValid',改用

var UserSchema = new Schema({
  email: { type: String, unique: true, required: true },
  pseudonyme: { type: String, unique: true, required: true },
  password: { type: String, required: true }
})

如果有错误,请将其保留为第一个参数EX: done(错误)否则使用null,EX: done(null,result)

const jwtLogin = new JwtStrategy(jwtOptions, function(payload, done) {  

var _id = mongoose.mongo.ObjectId(payload._id);

  User.find( {_id : _id} , function(err, user) {
        if (err) { return done(err); }

    if (user) {
      done(null, user);
    } else {
      done(new Error('User not found!!!'));
    }
  });
});

答案 1 :(得分:0)

尝试从架构中删除_id。

  var UserSchema = new Schema({
      email: { type: String, unique: true, required: true },
       pseudonyme: { type: String, unique: true, required: true },
       password: { type: String, required: true }
  });

尝试直接使用playload_id而不像下面那样强制使用

 User.findById( payload._id , function(err, user) {
    if (err) { return done(err, false); }

    if (user) {
      done(null, user);
    } else {
      done(null, false);
    }
  });

答案 2 :(得分:0)

我发现解决方案只是ExpressJS两条路线之间的路由冲突。

两者之间没有关系。

向所有人寻求帮助