Node.js错误无法读取未定义的属性“ then”

时间:2019-09-12 22:04:00

标签: node.js

function findall(collecionName) {

  var model = mongoose.model(collecionName, schema);

  model.find({}, (err, data) => {
    if (err) {console.log(err);} else {return data;} }
    }


//express router
express.get('/get', (req, res) => {
      return findall(collectionName).then((data) => {
        res.send(data);
      })

函数findall可以正常工作,但是当我导航到localhost:4200 / get时,出现错误'TypeError:无法读取未定义的属性'then'。

我是Node的新手,任何人都可以向我展示如何使其正常工作

2 个答案:

答案 0 :(得分:0)

经过研究后,我发现(...)。then(...);是一个承诺模式。因此,被调用函数;在上面的示例中,findall应该返回一个promise。因此,代码应如下所示:

function findall(collectionName){
return new Promise((resolve, reject)=>{
    var subModel = mongoose.model(subjectColl, schema);
    subModel.find({}, (err, data)=>{
        if(err){
            reject(err);
        }else{
            resolve(data);
        }
    })
})
 }

并且调用函数应该是:

 app.get('/get', (req, res, next)=>{
       findall(collectionName).then((data)=>{
              res.send(data);
          }) })

答案 1 :(得分:-1)

由于findall当前不返回任何内容,即undefined,因此调用.then会引发该错误。 model.find仅返回需要exec提取的查询对象才能获得Promise对象。此承诺对象需要由findall函数返回。请参阅以下文档,了解如何使用执行查询返回的Promise:https://mongoosejs.com/docs/api/model.html#model_Model.find

相关问题