这是我的模式
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
如何访问该功能?
您将findAll
添加为实例方法,而不是静态方法。如果你想为模型添加一个静态方法,那么你可以这样做:
testSchema.statics.findAll = async function (){
let tests = await this.find({});
return tests;
}
参见Statics