简体   繁体   中英

MongoDB - Mongoose.model.find returning an empty array

I have a simple Node.js app and I'm trying to communicate to MongoDB on localhost, but I can't seem to get any of the documents stored in the DB to be returned when I do a mongoose.model.find

There are clearly 2 documents in my DB when I use compass to explore it:

在此处输入图像描述

Here is my code:

var DB_HOST = 'localhost'
var DB_PORT = 27017

const options = {
    poolSize: 1000,
    keepAlive: 6000000,
    connectTimeoutMS: 6000000,
    autoReconnect: true,
    reconnectTries: 300000,
    reconnectInterval: 5000,
    useNewUrlParser: true
  };

module.exports = {
    'options' : options,
    'url' : 'mongodb://'+DB_HOST+':'+DB_PORT
};

mongoose.connect(configDB.url, configDB.options);

...

var mongoose = require('mongoose');

const messagesSchema = new mongoose.Schema({
    message: { type: String, required: true },
    year: { type: String, required: true }
});

const Message = mongoose.model('Message', messagesSchema);

async function getMessagesByYear(req, res) {
    try {
        const queryYear = req.headers.query;
        console.log("Get Messages by Year " + queryYear);

        const messages = await Message.find({ year: queryYear });
        console.log('messages: ' + messages);
        res.status(200).json(messages);
    } catch (err) {
        console.log("Unable to get messages", err);
        res.status(400).json({ message: "Unable to get messages" });
    }
}

Any suggestions or help will be appreciated!

Tried stepping through the code in debug mode, added printouts but can't see why the above function returns an empty array. Also checked the connection to my DB and it displays the correct status (2)

Your model will reference a collection named messages but the collection in your database is named Messages . You can either rename the collection, or specify the collection when making the model, like so:

const Message = mongoose.model('Message', messagesSchema, 'Messages');

Conventionally, collections are lowercase, so I recommend renaming the collection.

It also doesn't look like you're specifying the database to use when making a connection. You can either do this in the connection URI itself, or in the connection options. Doing it in the connection URI (which is the more common way) would look like this:

'mongodb://'+DB_HOST+':'+DB_PORT+'/message'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM