【发布时间】: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 -> })
-
是的,抱歉,这是一个复制和粘贴错误,我的架构更复杂,所以我简化了。