我正在尝试创建一个代表User的类,我希望它继承mongoose类的方法,它具有查找,保存,删除等功能。
我试图通过以下方式扩展猫鼬模型:class User extends Mongoose.model('User', UserSchema) {}
我的实际代码如下:
import { Mongoose } from '../config';
const Schema = Mongoose.Schema;
const UserSchema = new Schema({
email: { type: String, default: '' },
firstName: { type: String, default: '' },
lastName: { type: String, default: '' },
facebookId: { type: String, default: '' },
payments: { type: Array, default: [] }
});
const MongoUser = Mongoose.model('User', UserSchema);
class User extends MongoUser {
constructor(data) {
super();
this.email;
this.firstName;
this.lastName;
this.facebookId;
this.payments;
}
save(){
}
findUser(data){
return new Promise((resolve, reject) => {
super.findOne(data, (err, user) => {
if(err) {
console.log("err", err)
reject({err: err});
}
if(!user) {
console.log("No user found")
reject('No user found');
}
if(user){
console.log("user", user)
console.log("this", this)
this._set(user)
resolve(this);
}
});
})
}
_set(user){
this.email = user.email;
this.firstName = user.firstName;
this.lastName = user.lastName;
this.facebookId = user.facebookId;
this.payments = user.payments;
return;
}
}
export default User;
您将看到我正在尝试调用父类super.findOne()
的方法,但收到的错误[TypeError: Cannot read property 'call' of undefined]
让我感到难过。
没有堆栈跟踪,但错误在以下try / catch中被捕获:
exports.findUser = async (req, res) => {
let id = '58ad46dfb558dfe00efa9b02';
const user = new User();
try{
const loggedInUser = await user.findUser({_id: id});
res.send(loggedInUser);
}catch(e){
console.log("e", e)
res.send(e)
}
}
从我的路线调来:
router.get('/:userID', userController.findUser);
我是在正确的轨道上还是我试图延长猫鼬模型的方法?