【问题标题】:MongoDB Parse Error: URI does not have hostname, domain name and tld when connecting with localhostMongoDB Parse 错误:与 localhost 连接时 URI 没有主机名、域名和 tld
【发布时间】:2022-01-21 13:29:36
【问题描述】:

我正在尝试在本地连接 mongoDB。但由于某种原因,它会引发此错误。

'MongoParseError: URI 没有主机名、域名和 tld'

这是我的代码:

const DB = `mongodb://localhost/db_name`;
mongoose
  .connect(DB, {useNewUrlParser: true})
  .then(() => console.log('DB CONNECTION SUCCESSFUL!'))
  .catch(e => console.log('FAILED DB CONNECTION'));

我也试过用这个替换 db 字符串: mongodb://127.0.0.1:27017/db_name,但这也没有用。

【问题讨论】:

    标签: node.js mongodb express


    【解决方案1】:

    我的server.js 在下面,它可以工作。

    const express = require('express')
    const mongoose = require('mongoose')
    const Collection = require('./models/collection')
    const app = express()
    
    mongoose.connect('mongodb://localhost/db_name', {
        useNewUrlParser: true, useUnifiedTopology: true
    })
    
    app.set('view engine', 'ejs')
    app.use(express.urlencoded({ extended:false }))
    
    app.get('/', async (req,res) => {
        const docs = await Collection.find()
        res.render('index', { list : docs  })
    })
    
    app.listen(process.env.PORT || 5000);
    

    【讨论】:

    • 我无法理解,出于某种原因,我正在做完全相同的事情,这会引发错误。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-06-13
    • 2014-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-01
    • 1970-01-01
    相关资源
    最近更新 更多