简体   繁体   中英

mongoose connects only to localhost

I always get "Listening at localhost" but the URL I put is from Mongo Atlas. And when I print the environment variable to the console I get it correctly. mongoose automatically ignores any url other than localhost.

I have tried to restart nodemon muiltiple times.

mongoose
  .connect(process.env.DATABASE_URL, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
  })
  .then(() => {
    console.log(process.env.DATABASE_URL); //prints the correct url but mongoose connects to localhost
    console.log("mongo connected");
    // logEntry.collection.drop();
  })
  .catch((error) => console.log(error.message));

validate the connection using the below mentioned code snippet.

const express = require('express');
const app = express();
const socketio = require('socket.io');
const mongoose = require('mongoose');

const expressServer = app.listen(3001);
const io = socketio(expressServer);
mongoose.connect('mongodb+srv://<UserName>:<Password>@democluster0.abcde.mongodb.net?retryWrites=true&w=majority');

mongoose.connection.on('open', function (ref) {
    console.log('Connected to mongo server.');

    mongoose.connection.db.listCollections().toArray(function (err, names) {
        console.log(names);
    });
})

Refer the below link to gain the URL for the same..

https://docs.atlas.mongodb.com/tutorial/connect-to-your-cluster/

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