使用.find()返回空数组的Mongoose

时间:2017-12-10 20:51:23

标签: javascript node.js mongodb mongoose

我正在尝试使用Mongoose模块从我的应用程序查询MongoDB数据库中的数据,并且返回的是一个空数组。

SO中最常见的答案是Mongoose在创建模型时将集合名称复数化。但是,我相信我没有问题(如果实际上我做错了,请向我解释)。

此时,我尝试过的只是使用Result.find({},callback)选择所有条目,但同样,只返回一个空数组。

当我在命令行上查询数据时,我得到了预期的结果。下面我简单地检索了一个条目。

命令行上的Mongo shell:

> db.getName()
kaplanFfl
> db.getCollection('results')
kaplanFfl.results
> db.results.findOne({ Owner: 'Sample'})
{
        "_id" : ObjectId("5a24c90b46521500830aa042"),
        "Owner" : "Sample",
        "Pts" : 81.5,
        "Week" : 1,
        "SeasonAvg" : 86,
        "Lst8_Avg" : 92,
        "Lst4_Avg" : 91,
        "Mean" : 82,
        "High" : 116,
        "Low" : 55,
        "Diff" : 61,
        "Dev" : 16.49141822,
        "Elite" : 0,
        "Superior" : 0,
        "Inferior" : 0,
        "Abyssmal" : 0,
        "MeanPlus" : 0,
        "MeanMinus" : -1
}

这是代码:

model.js

'use strict';

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

let resultSchema = new Schema({
    Owner: String,
    Pts: Number,
    Week: Number,
    SeasonAvg: Number,
    Lst8_Avg: Number,
    Lst4_Avg: Number,
    Mean: Number,
    High: Number,
    Low: Number,
    Diff: Number,
    Dev: Number,
    Elite: Number,
    Superior: Number,
    Inferior:Number,
    Abyssmal: Number,
    MeanPlus: Number,
    MeanMinus: Number
})

let WeeklyResult = mongoose.model('result', resultSchema);

module.exports = WeeklyResult;

index.js

const express = require('express');
const app = express();

const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const Result = require('./models/models');

const PORT = process.env.PORT || 3000;

//username and password has been removed, but it does connect
const uri = 'mongodb://<username>:<password>@kaplanffl-shard-00-00-rmbku.mongodb.net:27017,kaplanffl-shard-00-01-rmbku.mongodb.net:27017,kaplanffl-shard-00-02-rmbku.mongodb.net:27017/kaplanFfl?ssl=true&replicaSet=kaplanFfl-shard-0&authSource=admin'


//open the connection to the database
mongoose.Promise = global.Promise;

mongoose.connect(uri, {
    useMongoClient: true
})

let db = mongoose.connection;

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

db.on('error', console.error.bind(console, 'Connection error: '));
db.once('open', function() {

    console.log('Connection to MongoDB is live. Database: ' + db.name);
    Result.find({}, function(err, results) {
        if (err) console.log(err);
        console.log(results);
    })
})


//start web server
app.listen(PORT, (req, res) => {
    console.log('Server live on port ' + PORT);
});

我希望得到所有结果,但只能在控制台中获得以下内容:

Server live on port 3000
Connection to MongoDB is live. Database: kaplanFfl
[]

所以,我觉得好像多元化问题被掩盖了,对吧?我已经尝试了很多关于SO的方法,但仍然得到了相同的结果。

感谢任何帮助!

0 个答案:

没有答案