简体   繁体   English

MongoDB - Mongoose.model.find 返回一个空数组

[英]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我有一个简单的 Node.js 应用程序,我正在尝试与本地主机上的 MongoDB 通信,但是当我执行 mongoose.model.find 时,我似乎无法返回存储在数据库中的任何文档

There are clearly 2 documents in my DB when I use compass to explore it:当我使用指南针探索它时,我的数据库中显然有 2 个文档:

在此处输入图像描述

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.尝试在调试模式下单步执行代码,添加了打印输出但看不出为什么上面的 function 返回一个空数组。 Also checked the connection to my DB and it displays the correct status (2)还检查了与我的数据库的连接,它显示了正确的状态 (2)

Your model will reference a collection named messages but the collection in your database is named Messages .您的 model 将引用名为messages的集合,但数据库中的集合名为Messages You can either rename the collection, or specify the collection when making the model, like so:您可以重命名集合,也可以在制作 model 时指定集合,如下所示:

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

Conventionally, collections are lowercase, so I recommend renaming the collection.按照惯例,collections 是小写的,所以我建议重命名该集合。

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.您可以在连接 URI 本身或连接选项中执行此操作。 Doing it in the connection URI (which is the more common way) would look like this:在连接 URI 中执行此操作(这是更常见的方式)将如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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