Mongoose Model.find不是一个函数?

dum*_*e92 14 mongoose mongodb node.js

花了好几个小时试图解决这个问题 - 我正在为我的应用添加一个新模型,但是它失败了"TypeError:List.find不是一个函数".我有另一个模型,项目,以相同的方式设置,并正常工作.事情似乎在路线上失败但是如果我把它连接到Item模型就可以了.我是否错误地声明了架构?我是否需要在mongo或其他东西中启动模型?

模型

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

var listSchema = new Schema({
    name: { type: String, default: datestring + " List" }
});

mongoose.exports = mongoose.model('List', listSchema);
Run Code Online (Sandbox Code Playgroud)

路线

app.get('/lists', function (req, res, err) {
    List.find(function (err, docs){ //THIS IS WHAT'S FAILING
        res.json(docs);
    });
});
Run Code Online (Sandbox Code Playgroud)

调节器

angular.module('pickUp').controller('ListsCtrl', ['$scope', '$http', 'ngDialog', 'lists',

        function($scope, $http, ngDialog, lists) {

        $scope.lists = lists.lists;

    }]);
Run Code Online (Sandbox Code Playgroud)

厂

angular.module('pickUp').factory('lists', ['$http',
    function($http){

        var lists = {
            lists: []
        };

        lists.getAll = function(){
            console.log("trying. . .");
            $http.get('/lists').success(function(res){
                angular.copy(res, lists.lists);
            });
        };

        return lists;
}]);
Run Code Online (Sandbox Code Playgroud)

配置

$stateProvider
.state('/', {
    url: '/',
    templateUrl: 'views/lists.html',
    controller: 'ListsCtrl',
    resolve: {
        listPromise: ['lists', function (lists){
            return lists.getAll();
        }]
Run Code Online (Sandbox Code Playgroud)

AfD*_*Dev 30

您的模块导出不正确

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

var listSchema = new Schema({
    name: { type: String, default: datestring + " List" }
});

**mongoose.exports = mongoose.model('List', listSchema);** <!-- this is wrong -->
Run Code Online (Sandbox Code Playgroud)

它应该是

**module.exports = mongoose.model('List', listSchema)**
Run Code Online (Sandbox Code Playgroud)

  • 我完全按照你的建议做,但发生了同样的错误。 (4认同)

小智 7

我遇到了这个问题。要解决这个问题,您需要了解一个逻辑。您需要调用.find从模型文件导入的模型作为承诺。

例子:

const member = require('..// path to model')

//model initiation
const Member = new member();

exports.searchMembers = function (req,res) {


Member.find({},(err,docs)=>{
    res.status(200).json(docs)
})

}
Run Code Online (Sandbox Code Playgroud)

此代码不起作用,因为我调用find()了已启动的架构

有效的代码:

exports.searchMembers = function (req,res) {


member.find({},(err,docs)=>{
    res.status(200).json(docs)
})

}
Run Code Online (Sandbox Code Playgroud)

在这里我.find()直接调用导入模型