猫鼬在执行Model.find()查询时从我的数据库返回一个空数组

时间:2018-11-14 18:44:28

标签: mongodb express mongoose

I looked at this popular question,但似乎无法解决我的问题,因此我将其发布。

我目前有一个使用mongoose的express.js服务器文件,该文件一直返回一个空数组。我不知道是否可能是由于异步问题,而且我不知道该用什么来表明我已连接到数据库。

const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const PORT = process.env.PORT || 8080;


//Mongoose stuff
mongoose.connect('mongodb+srv://excelsiorAdmin:Mysecretpassword@excelsiorcluster-zakfd.mongodb.net/test?retryWrites=true', { useNewUrlParser: true, dbName: 'excelsiorDB'});
const dbConnection = mongoose.connection;

dbConnection.on('error', console.error.bind(console, 'connection error:'));
dbConnection.once('open', function() {
    console.log('connected to the database');

    let charSchema = new mongoose.Schema({
        imageURL: String,
        company: String,
        name: String,
        civName: String,
        alignment: String,
        firstDebut: String,
        abilities: Array,
        teams: Array,
        desc: String
    });

    let Char = mongoose.model('Char', charSchema, 'chars');

    //root
    app.get('/', (req, res, next) => res.send('Welcome to the API!'));

    //get all characters
    app.get('/chars', (req, res, next) => {
        console.log('getting all characters');
        Char.find(function (err, chars) {
            if (err) {
                res.status(404).send(err);
                console.log('there was an error');
              };
              console.log(chars);
              res.send(chars);
        });
    });

    //get heroes
    app.get('/chars/heroes', (req, res, next) => {
        Char.find({alignment: "Hero"}, function (err, chars) {
            if (err) {
                res.status(404).send(err);
            };
            res.send(chars);
        });
    });

});

app.listen(PORT, () => console.log(`This API is listening on port ${PORT}!`));

1 个答案:

答案 0 :(得分:0)

mongoose.model会将要查找的集合设置为等于模型名称的小写,复数形式。

let Char = mongoose.model('Char', charSchema);

这将寻找“字符”集合。但是,如果您要连接的数据库没有名称与猫鼬默认名称相同的集合,它将从不存在的集合中返回结果。为了确保它匹配正确的集合(如果它们不匹配),您必须手动输入集合的名称作为第三个参数:

let Char = mongoose.model('Char', charSchema, "excelsiorCollection");