Mongoose Model find()返回带有节点js的空数组

时间:2017-03-22 03:58:29

标签: node.js express mongoose

当我尝试使用mongoose模型从数据库中获取数据时,我总是得到空数组。 我使用带有express的nodejs通过使用find()函数使用mongoose从mongodb获取数据。

但是当我在mongoshell中使用db.collectionname.find({});时,我获得了所有的值。

以下是我的型号代码:

var mongoose = require('mongoose');
mongoose.set('debug', true);
var schema = mongoose.Schema;

var countriesSchema = new schema({
    id : {
        type : Number,
        required : true
    },
    code : {
        type : String,
        required :true
    },
    name : {
        type : String,
        required : true
    },
    phonecode : {
        type : Number,
        required : true
    }
});

var Countries = module.exports = mongoose.model('Countries', countriesSchema);

module.exports.getCountries = function(callback){
    Countries.find({}, callback);
}

以下是我的路由文件代码:

var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var router = express.Router();
var configMain = require('./../config/main');
var https = require('https');
var querystring = require('querystring');
var countriesModel = require('./../database/models/countries.model');
var statesModel = require('./../database/models/states.model');
var citiesModel = require('./../database/models/cities.model');


router.get('/get-country-city-state',function(req, res, next){
    var response = {};
    if(req.query.type == "getCities"){
        citiesModel.getCities(req.query.stateId, function(err, cities){
            sendResponse(err, cities);
        });
    }else if(req.query.type == "getStates"){
        statesModel.getStates(req.query.countryId, function(err, states){
            sendResponse(err, states);
        });
    }else if(req.query.type == "getCountries"){
        countriesModel.getCountries(function(err, countries){
            sendResponse(err, countries);
        });
    }else{
        sendResponse(err, null);
    }
    //res.send($response);
});

function sendResponse(err, data){
    if(err){
        res.send(err);
    }
    console.log(data);return;
    /*for(var i = 0; i <= data.length; i++){

    }
    response = {'success' : 1, 'result' : dataResult};*/
}

module.exports = router;

在我的数据库中,我有以下数据:

  {
       "_id": ObjectId("58d018733b3161574df5ebe1"),
       "id": 1,
       "code": "AF",
       "name": "Afghanistan",
       "phonecode": 93
   }

在我的console.log(data)中,当我拿到所有国家时,我正在变空阵列。

0 个答案:

没有答案