从节点上的MongoDb检索数据失败.Js API



我有一个托管在Azure上的MongoDb服务器。我现在正在构建一个Node.js API,用于从其中一个数据库上的表(即表:Word;数据库:MyDatabase(中检索数据。我已经按照本教程构建了API,但我无法成功地从中检索任何数据…

我知道服务器已经启动并运行,也可以访问,因为我可以通过以下方式tcp连接到它:

psping [Azure's Public IP]:27017

现在,我有了一个node.js api,其中包含以下代码:1( app/server.js

var express    = require('express');        // call express
var app        = express();                 // define our app using express
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
mongoose.connect('mongodb://[Azure's public IP]:27017/MyDatabase');
var Word = require('./models/word');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var port = process.env.PORT || 8080;        // set our port
// ROUTES FOR API
var router = express.Router();              // get an instance of the express Router
// middleware to use for all requests
router.use(function(req, res, next) {
    // do logging
    console.log('Something is happening.');
    next();
});
router.get('/', function(req, res) {
    res.json({ message: 'hooray! welcome to our api!' });   
});
router.route('/words')
    .get(function(req, res) {
        Word.find(function(err, words) {
            if (err)
                res.send(err);
            res.json(words);
        });
    });
// more routes for our API will happen here
// REGISTER OUR ROUTES -------------------------------
// all of our routes will be prefixed with /api
app.use('/api', router);
// START THE SERVER
// =============================================================================
app.listen(port);
console.log('Magic happens on port ' + port);

我还为数据库中唯一的表编写了一个模型,该表有3列:自动生成的ObjectId、西班牙语、法语(意味着要有两种语言的单词,使其能够作为翻译器工作(。模型如下:2(app/models/word.js

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var WordSchema = new Schema({
    spanish: String,
    french: String
})
var Word = mongoose.model('Word',WordSchema);
module.exports = Word;

现在,我去找邮递员,然后点击以下内容:http://localhost:8080/api/words;返回[]。

在MongoDb日志上,我看到以下内容:

2016-08-05T03:16:26.520+0000 I NETWORK  [conn60] end connection [Some IP]:[Some port] (1 connections now open)
2016-08-05T03:31:11.878+0000 I NETWORK  [initandlisten] connection accepted from [Some IP]:[Some port] #61 (1 connection now open)

正如您在评论中提到的,文档是从db.word.find()检索到的,我想我发现了问题。您需要将文档放入名为words而不是word的集合中。

Mongoose将使用复数版本的模型名称。看见http://mongoosejs.com/docs/models.html了解更多信息。

我认为您在查找时缺少{}

router.route('/words')
.get(function(req, res) {
    Word.find({}, //Added here.
      function(err, words) {
        if (err)
            res.send(err);
        console.log(words)
        res.json(words);
    });
});

希望这会有所帮助。

编辑:-

根据doc的文档,find函数接受第一个参数作为对象,并将其视为条件,但不接受回调函数。

最新更新