【问题标题】:NodeJs mongoose CastError on method findById方法 findById 上的 NodeJs mongoose CastError
【发布时间】:2016-10-27 08:10:56
【问题描述】:

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

mongoose.Types.ObjectId.isValid(_id);测试我的_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);

【问题讨论】:

  • _id 类型应该是 Schema.Types.ObjectId
  • 我测试了新的 mongoose.Schema.Types.ObjectId('_id') 并且我有错误 CastError: Cast to ObjectId failed for value "ObjectId
  • 如果 _id 是 ObjectId,则无需在架构中定义。无论如何,您能否更新您的问题以显示调用 findById 的代码以及它传递给该调用的值?
  • 请先编辑,这里的括号和括号已更改:密码:{ type: String, required: true } -> )} ---> to -> })
  • 是的,抱歉,这是一个复制和粘贴错误,我的架构更复杂,所以我简化了。

标签: node.js mongodb mongoose


【解决方案1】:

我找到了解决方案,它只是 ExpressJS 的两条路由之间的路由冲突。

两者之间没有任何关系。

感谢所有人的帮助

【讨论】:

    【解决方案2】:

    尝试从架构中删除 _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);
        }
      });
    

    【讨论】:

    • Same Error CastError: Cast to ObjectId failed for value "protected" at path "_id"
    【解决方案3】:

    首先不要在你的 Schema 中定义 _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(err) 否则使用 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!!!'));
        }
      });
    });
    

    【讨论】:

    • 架构中“_id”的代码和注释定义相同的错误
    • 你能给我看看型号代码吗,我想问题出在 module.exports
    • 在您编辑架构并删除“_id”后,如果您没有关于集合的信息,您可以将其删除并重新测试吗?!
    • 删除用户收藏同样的问题
    • 更改 findById(_id, .. by find({_id:_id},... ,因为此错误意味着“_id”为空或为空
    猜你喜欢
    • 2015-07-16
    • 1970-01-01
    • 1970-01-01
    • 2014-01-14
    • 2017-05-18
    • 2019-07-14
    • 2018-09-16
    • 2018-06-11
    • 1970-01-01
    相关资源
    最近更新 更多