简体   繁体   中英

Mongoose.connect via async try await catch errors nodejs followed by connecting to mongo database

I am following a tutorial to learn to correctly connect to mongodb with mongoose using async function. Should be simple but can't figure this out after 2 days. It will connect me but it gives me errors first even though I believe I account for the errors? Not sure how to get rid of the errors.

ERRORS:

    (node:95496) DeprecationWarning: current URL string parser is deprecated, and will be 
    removed in a future version. To use the new parser, pass option { useNewUrlParser: true } to 
    MongoClient.connect.
    (Use `node --trace-deprecation ...` to show where the warning was created)
    Server Started on port ${PORT}
    (node:95496) [MONGODB DRIVER] Warning: Top-level use of w, wtimeout, j, and fsync is 
    deprecated. Use writeConcern instead.
    (node:95496) [MONGODB DRIVER] Warning: Current Server Discovery and Monitoring engine is 
    deprecated, and will be removed in a future version. To use the new Server Discover and 
    Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.
    Mongodb Connected...
    /* #1 default.json INSIDE CONFIG FOLDER --> Info is correct and mongo atlas has ip of device added */

    {
        "MONGO_URI": "mongodb+srv://name:password@cluster0.9jhpi.mongodb.net/myFirstDatabase?retryWrites=true&w=majority"
    }
    /* #2 db.js INSIDE THE CONFIG FOLDER */

    //Bring in the libraries needed
    const mongoose = require('mongoose');
    const config = require('config');

    //get the mongoURI global variable from config package and save into variable called db
    const db = config.get('MONGO_URI');

    //connect to mongoDB using async await promise arrow function
    mongoose.connect(db)
    const connectDB = async () => {
        try { //if try works 
            await mongoose.connect(db, {
                useNewUrlParser: true,
                useCreateIndex: true,
                useFindAndModify: false,
                useUnifiedTopology: true
              }); 
            console.log('Mongodb Connected...');
        } catch(err){ //if try fails
            console.error(err.message);
            //exit process with failure
            process.exit(1);
        }
    }
    //allow file export
    module.exports = connectDB;
    /* #3 server.js INSIDE THE ROOT FOLDER */

    //Add express
    const express = require('express');

    //Add mongo db
    const connectDB = require('./config/db');


    //initialize app variable with express
    const app = express();



    //single endpoint for testing sends message to browser window
    app.get('/', (req, res) => res.send('API Running'));

    //Init middleware --> replaces the old body parser
    app.use(express.json({extended: false}));

    //Define Routes
    app.use('/api/users', require('./routes/api/users'));
    app.use('/api/auth', require('./routes/api/auth'));
    app.use('/api/profile', require('./routes/api/profile'));
    app.use('/api/posts', require('./routes/api/posts'));

    //add the remote (environment variable) or local port number
    const PORT = process.env.PORT || 5000;

    //Pass in the port and do a call back
    app.listen(PORT, () => console.log('Server Started on port ${PORT}'));

    //Connect database
    connectDB();

This part in your code is strange:

    //connect to mongoDB using async await promise arrow function
    mongoose.connect(db); // you need to remove this line
    
    const connectDB = async () => {
        try { //if try works 
            await mongoose.connect(db, {
                useNewUrlParser: true,
                useCreateIndex: true,
                useFindAndModify: false,
                useUnifiedTopology: true
              }); 
            console.log('Mongodb Connected...');
        } catch(err){ //if try fails
            console.error(err.message);
            //exit process with failure
            process.exit(1);
        }
    }

    //allow file export
    module.exports = connectDB;```

You export the connectDB method to use it in another file, so you don't need the line mongoose.connect(db) . You can remove this line and restart your program to see whether the messages disappear.

The messages you have, are actually warnings.

1.

(node:95496) DeprecationWarning: current URL string parser is deprecated, and will be 
    removed in a future version. To use the new parser, pass option { useNewUrlParser: true } to 
    MongoClient.connect.

this is because in mongoose.connect() line, you don't have the option useNewUrlParser . I think this warning will disappear after removing that line.

2.

  (node:95496) [MONGODB DRIVER] Warning: Current Server Discovery and Monitoring engine is 
    deprecated, and will be removed in a future version. To use the new Server Discover and 
    Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.
    Mongodb Connected...```

same as above for useUnifiedTopology option.

3.

 (node:95496) [MONGODB DRIVER] Warning: Top-level use of w, wtimeout, j, and fsync is 
    deprecated. Use writeConcern instead.

You can search for this error, I found a similar discussion here where people add this to connection options:

writeConcern: {
        j: true,
    },

You can also check the mongoose document here

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