【发布时间】:2022-02-09 01:38:33
【问题描述】:
当使用 mongoose 聚合时,它会返回一个 ProfileDocuments 数组。 结果数组中的 Documents 不包含 ProfileDocument 实现的方法。 这导致无法对数据库中的文档调用 checkPassword 等文档方法。
聚合示例
ProfileSchema.statics.findByLogin = async function (login: string) {
// why do methods of aggregated documents not work?
const results = await this.aggregate([{
$match: {
$or:[{username: login}, {mail: login}]
}
}])
if (results.length === 0) {
throw new Error('Profile not found')
}
const profile = await this.findById(results[0]._id)
console.log(results[0].checkPassword)
console.log(profile.checkPassword)
return profile
}
控制台输出
undefined
[Function (anonymous)]
方法实现
interface ProfileDocument extends IProfile, Document {
getDisplayname: () => Promise<string>
}
ProfileSchema.methods.checkPassword = async function (password: string) {
return await bcrypt.compare(password, this.pass)
}
【问题讨论】:
标签: typescript mongoose methods model aggregate