Mongoose与MongoDB Atlas返回空数组

时间:2019-03-27 20:59:14

标签: node.js database mongodb express mongoose

我正在尝试将express.js与MongoDB Atlas和mongoose连接,但是服务器始终返回一个空数组'[]'。当我加载本地数据库时,一切正常(MongoDB在本地和MongoDB Atlas具有相同的值)

控制器:

const mongoose = require('mongoose');
const HistoryData = require('../models/databaseHistory');

exports.data = (req, res) => {
    res.header("Access-Control-Allow-Origin", "*");
    mongoose.connect('mongodb+srv://olechbartlomiej:<myPass>@quizapp-mpygt.mongodb.net/test?retryWrites=true', {useNewUrlParser: true});
    mongoose.Promise = global.Promise;
    HistoryData.find({ type : 'question' }).then((historyData) => {
        res.send(historyData)
    })
}

模式:

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

const dataSchema = new Schema({
    type: {
        type: String
    },
    data: {
        type: String
    }
})

const HistoryData = mongoose.model('history', dataSchema);
module.exports = HistoryData;

MongoDB Atlas集合: (数据库名称:test,集合名称:history)

    _id : 5c9bdb721c9d440000345d62
    type : "question"
    data : "test test"

屏幕:MongoDB Atlas screen

服务器返回[]

1 个答案:

答案 0 :(得分:1)

连接时,需要指定数据库名称作为选项。 将options对象更新为此: {useNewUrlParser: true, dbName: "YOUR-DB-NAME-HERE"}