Mohit Ashliya
Mohit Ashliya

Reputation: 645

find() method not working withn an async functionin mongoose

I am trying to get all the documents in command prompt or simply console.log() but the find() method is not working here is my code and what it shows on running.

const mongoose = require('mongoose');


//connection creation and create a new db
mongoose.connect("mongodb://localhost:27017/mohitChannel").then(()=> console.log("connection successful")).catch((err) => console.log(err));
 // these then and catch are the promise taker


 // and now schema
 const playListSchema = mongoose.Schema({
   //  name: String, there are two ways one it is and other is given below.
   name: {
       type: String,
       required: true
   },
     videos: Number,
     active: Boolean,
     author: String,
     date: {
         type: Date,
         default: Date.now
     }
 })   




const Playlist = mongoose.model("PlayList", playListSchema); // collection named playlists created.


const getDocument = async () => {
   const result = await Playlist.find()
   console.log(result);
}

 getDocument();

And it is showing this

C:\nodeMongo>node src/app.js connection successful (node:16088) UnhandledPromiseRejectionWarning: MongoInvalidArgumentError: Method "collection.find()" accepts at most two arguments at Collection.find (C:\nodeMongo\node_modules\mongodb\lib\collection.js:238:19) at NativeCollection. [as find] (C:\nodeMongo\node_modules\mongoose\lib\drivers\node-mongodb-native\collection.js:191:33) at NativeCollection.Collection.doQueue (C:\nodeMongo\node_modules\mongoose\lib\collection.js:135:23) at C:\nodeMongo\node_modules\mongoose\lib\collection.js:82:24 at processTicksAndRejections (internal/process/task_queues.js:77:11) (Use node --trace-warnings ... to show where the warning was created) (node:16088) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag --unhandled-rejections=strict (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1) (node:16088) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

I tried the catch block but still it is not working

Upvotes: 0

Views: 704

Answers (3)

NeNaD
NeNaD

Reputation: 20404

Try to pass empty object to find() as a first parameter:

const result = await Playlist.find({})

Upvotes: 0

oieduardorabelo
oieduardorabelo

Reputation: 2985

by the time you execute your script with node src/app.js, the line on where you executed getDocument() will run before the mongodb database connection is set,

you are using a promise to connect to mongo database, this is an asynchronous tasks that happens on the background: mongoose.connect(...).then(...)

mongoose.connect start executing, since there's nothing stopping your script to "wait for the database connection", it will continue to the next line until it reaches getDocument(), in this moment, the connection with the database is not set yet, that's why you are receiving an error (the error message is not helpful in this case),

to fix your issue, you can move everything inside the mongoose.connect(...).then(<all-code-here>), like this:

const mongoose = require('mongoose');

//connection creation and create a new db
mongoose
  .connect('mongodb://localhost:27017/mohitChannel')
  .then(() => {
    console.log('connection successful');
    // and now schema
    const playListSchema = mongoose.Schema({
      //  name: String, there are two ways one it is and other is given below.
      name: {
        type: String,
        required: true,
      },
      videos: Number,
      active: Boolean,
      author: String,
      date: {
        type: Date,
        default: Date.now,
      },
    });

    const Playlist = mongoose.model('PlayList', playListSchema); // collection named playlists created.

    const getDocument = async () => {
      const result = await Playlist.find();
      console.log(result);
    };

    getDocument();
  })
  .catch((err) => console.log(err));
// these then and catch are the promise taker

and since you are using async functions, you can transform everything in async/await pattern:

const mongoose = require('mongoose');

async function main() {
  await mongoose.connect('mongodb://localhost:27017/mohitChannel');
  console.log('connection successful');

  const playListSchema = mongoose.Schema({
    name: {
      type: String,
      required: true,
    },
    videos: Number,
    active: Boolean,
    author: String,
    date: {
      type: Date,
      default: Date.now,
    },
  });

  const Playlist = mongoose.model('PlayList', playListSchema);

  const getDocument = async () => {
    const result = await Playlist.find();
    console.log(result);
  };

  getDocument();
}

try {
  main();
} catch (err) {
  // in case the database connection fails, do something
  console.log(err);
}

Upvotes: 1

mohammad Naimi
mohammad Naimi

Reputation: 2359

This issue is facing mongoose version 6.0 So you just have to downgrade the mongoose version. Just run npm uninstall mongoose to uninstall the current mongoose version then run npm i mongoose@5.13.8 this will install the version that will fix your problem

Upvotes: 0

Related Questions