猫鼬只连接到本地主机

时间:2020-10-12 10:52:21

标签: node.js mongodb express mongoose

我总是会收到“在本地主机上收听”,但我输入的URL来自Mongo Atlas。当我将环境变量打印到控制台时,我可以正确获取它。猫鼬会自动忽略除本地主机以外的任何URL。

我试图重启nodemon多次。

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));

1 个答案:

答案 0 :(得分:0)

使用下面提到的代码段验证连接。

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);
    });
})

请参考下面的链接以获取相同的URL。

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