【问题标题】:Data is not being fetched from mongo database.receiving an empty error.Although collection is present in mongo cloud未从 mongo 数据库中获取数据。收到一个空错误。尽管 mongo 云中存在集合
【发布时间】:2020-04-12 18:16:57
【问题描述】:

我无法通过我的获取请求接收数据。它返回一个空数组,尽管当我签入 Mongo Cloud 服务器时,它具有所有集合。我对同一数据库的另一个集合“用户”使用相同的流程和代码,并且工作正常。谁能指出错误. 我已经提供了 Router=>model=>connection 文件。 [在此处输入图片描述][1]connection.js

const Schema = mongoose.Schema;
mongoose.set('useCreateIndex', true)

const url = process.env.ATLAS_URI;
mongoose.connect(url, { useNewUrlParser: true }
);

const connection = mongoose.connection;
connection.once('open', () => {
    console.log("MongoDB database connection established successfully");
})


let userSchema = new Schema({
    username: {
        type: String,
        required: true,
        unique: true,
        trim: true,
        minlength: 3
    },
}, {
    timestamps: true,
}, { collection: 'users' });


let exerciseSchema = new Schema({
    username: {
        type: String,
        required: true
    },
    description: {
        type: String,
        required: true,
    },
    duration: {
        type: Number,
        required: true
    },
    date: {
        type: Date,
        required: true
    }
}, {
    timestamps: true,
}, { collection: 'exercises' });


var collection = {}

collection.getUser = () => {
    return mongoose.connect(url, { useNewUrlParser: true })
        .then((database) => {
            return database.model('users', userSchema)
        }).catch((err) => {
            return (err + 'Connection couln\'t be established to user database')
        })
}

collection.getExercise = () => {
    return mongoose.connect(url, { useNewUrlParser: true })
        .then((database) => {

            return database.model('exercises', exerciseSchema)
        }).catch((err) => {
            return (err + 'Connection couln\'t be established to exercise database')
        })
}
module.exports = collection;```


  [1]: https://i.stack.imgur.com/moT2z.png

【问题讨论】:

    标签: node.js json api post backend


    【解决方案1】:

    使用需要使用 find 或 findOne 查询

    return database.model(...).find({}).exec();
    

    欲了解更多信息https://mongoosejs.com/docs/queries.html

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-11-17
      • 2022-10-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多