TypeError:Test.findAll不是函数callinf猫鼬模式

时间:2020-11-03 18:02:54

标签: javascript node.js mongoose

这是我的模式

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const testSchema = Schema({
    title: String,
    questions: [],
    user: Schema.Types.ObjectId
});

testSchema.methods.findAll = async function (){

    let tests = await this.find({});

    return tests;
}


module.exports = mongoose.model('Test',testSchema)

我想在此功能上使用它

showMainPage = function(req, res){
    var tests = Test.findAll();
    console.log(tests);
    res.render('main/index.twig', {username:req.user.username});
}

但是我收到此错误消息

TypeError: Test.findAll is not a function

如何访问该功能?

1 个答案:

答案 0 :(得分:0)

您添加了findAll作为实例方法,而不是静态方法。如果您希望为模型添加静态方法,则可以执行以下操作:

testSchema.statics.findAll = async function (){

    let tests = await this.find({});

    return tests;
}

请参见Statics