Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose with MongoDB Atlas return empty array

I'm trying to connect express.js with MongoDB Atlas and mongoose but server always returns an empty array '[ ]'. When I load a local database everything works (MongoDB locally and MongoDB Atlas have the same values)

Controller:

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)
    })
}

Schema:

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 collection: (Database name : test, collection name : history)

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

screen: MongoDB Atlas screen

And the server returns [ ]

like image 501
Bartłomiej Olech Avatar asked Nov 22 '25 14:11

Bartłomiej Olech


1 Answers

You need to specify the database name as an option when connecting. Update the options object to this: {useNewUrlParser: true, dbName: "YOUR-DB-NAME-HERE"}

like image 112
Darren Weston Avatar answered Nov 24 '25 07:11

Darren Weston



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!