简体   繁体   中英

Mongo query not producing results in my main server

I tried to make use of promises to get all the items from my mongoDB database. This is my code:

exports.findAll = function(){
  return new Promise(function(resolve, reject){
      Collection.find({}, function(err, res){
        if(err){
          reject(err);
        } else {
          console.log(res);
          resolve(res);
        }
      });
  });
}

However, when I call the findAll() function, the result is an empty array. I have checked my connection to the database, and it is successfully established. And the database itself is non-empty too. I cannot figure out what I am doing wrong. Any help is appreciated. Thanks in advance!

You can use mongoose for comfortable use of MongoDB

import mongoose from 'mongoose';

Create a connection

await mongoose.connect('mongodb://localhost/my_database', {
  useNewUrlParser: true,
  useUnifiedTopology: true,
  useFindAndModify: false,
  useCreateIndex: true
});

Create your model for the collection

const collection= new Schema({
  _id: ObjectId,
  name: String,
  age: Number,
});

const Collection= mongoose.model('Collection', collection);


const data = await Collection.find({});

Here you can find more information check Mongoose documentation

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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