【问题标题】:mongodb/mongoose returning empty array when finding allmongodb/mongoose 查找全部时返回空数组
【发布时间】:2021-03-31 00:24:52
【问题描述】:

我正在为现有的 mongodb Atlas 集群编写 Node.js 后端。

我跑步时的路线

const routes = (app) => {
    app.route('/file')
        .get((req, res, next) => {
            console.log('request from : ' + req.originalUrl)
            console.log('request type : ' + req.method)
            next();
        }, getFiles);
}

其中getFiles如下:

const ChronicFile = mongoose.model('File', FileSchema);
export const getFiles = (req, res) => {
    ChronicFile.find({}, (err, chronicFile) => {
        if (err) {
            res.send(err);
        }
        console.log(chronicFile);
        res.json(chronicFile);
    });
}

我得到一个空白数组返回:

ur server running on port4000
request from : /file
request type : GET
[]

根据 mongodb shell 的 db 结构是标题为 Chronic 的整体 db 和标题为 Chronic Filesfs.chunksfs.files 的三个集合。我的目标是查询 fs.files 集合并从那里获取所有内容。

fs.files 集合内的方案如下:

{
   "_id":{
      "$oid":"604e57219ffdaa7e11a8edad"
   },
   "length":{
      "$numberLong":"3163108"
   },
   "chunkSize":261120,
   "uploadDate":{
      "$date":"2021-03-14T18:34:10.586Z"
   },
   "filename":"4-dance-a-complex.mp3",
   "metadata":{
      
   }
}

我的猫鼬模式如下:

import mongoose from 'mongoose';

const Schema = mongoose.Schema;

export const FileSchema = new Schema({
    id: {
        type: mongoose.Types.ObjectId
    },
    chunkSize : {
        type: Number
    },
    fileName : {
        type: String
    },
    length: {
        type: Number
    },
    metadata : {
        type: Object
    },
    uploadDate : {
        type: Date
    }
}, { collection : 'Chronic.fs.files'});

我添加了如上所示的集合名称,因为我查看了以前的 stackoverflow 帖子,它们有一个命名问题。我在这里做错了什么还是我错过了其他东西?当我在 mongo shell 上执行 db.getName() 时,它会显示 Chronic,而当我执行 db.fs.files.find() 时,它会输出该集合中的所有条目。

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    答案就在这段代码中:

    const ChronicFile = mongoose.model('File', FileSchema);
    export const getFiles = (req, res) => {
        ChronicFile.find({}, (err, chronicFile) => {
            if (err) {
                res.send(err);
            }
            console.log(chronicFile);
            res.json(chronicFile);
        });
    }
    

    我需要将实际的集合名称传递给 mongoose 模型,而不仅仅是 File

    【讨论】:

      猜你喜欢
      • 2017-09-12
      • 2017-11-13
      • 1970-01-01
      • 2019-08-18
      • 2012-02-23
      • 2018-06-12
      • 2021-09-17
      • 2021-07-22
      • 2016-03-24
      相关资源
      最近更新 更多