element.find不是一个函数

时间:2018-03-05 20:30:31

标签: node.js rest api express

我正在学习如何制作REST Api并完全复制tutorial's代码,但它给了我这个错误:

TypeError: Bear.find is not a function
at /Users/madisontaskett/instaApi/server.js:67:14
at Layer.handle [as handle_request] (/Users/madisontaskett/instaApi/node_modules/express/lib/router/layer.js:95:5)
at next (/Users/madisontaskett/instaApi/node_modules/express/lib/router/route.js:137:13)
at next (/Users/madisontaskett/instaApi/node_modules/express/lib/router/route.js:131:14)
at Route.dispatch (/Users/madisontaskett/instaApi/node_modules/express/lib/router/route.js:112:3)
at Layer.handle [as handle_request] (/Users/madisontaskett/instaApi/node_modules/express/lib/router/layer.js:95:5)
at /Users/madisontaskett/instaApi/node_modules/express/lib/router/index.js:281:22
at Function.process_params (/Users/madisontaskett/instaApi/node_modules/express/lib/router/index.js:335:12)
at next (/Users/madisontaskett/instaApi/node_modules/express/lib/router/index.js:275:10)
at /Users/madisontaskett/instaApi/server.js:35:5

这是我的代码段:

.get(function(req, res) {

    var Bear = require('./api/models/instaApiModel');
    Bear.find(function(err, bears) {
        if (err)
            res.render(err);

        res.json(bears);
    });
});

1 个答案:

答案 0 :(得分:0)

看起来问题是关于加载Bear模型。

// Bear models lives here
var Bear = require('./app/models/bear'); 

您还需要确保按如下方式创建模型:

// app/models/bear.js    
var mongoose = require('mongoose');
var Schema   = mongoose.Schema;

var BearSchema = new Schema({
    name: String
});

module.exports = mongoose.model('Bear', BearSchema);

有关完整的源代码,请参阅this link