【问题标题】:Can't connect to mongoDB with node.js using mongoose无法使用 mongoose 通过 node.js 连接到 mongoDB
【发布时间】:2019-10-15 18:45:58
【问题描述】:

这是我写的代码:

const mongoose = require('mongoose')
const userSchema = require('./userSchema.js')
const User = mongoose.model('user', userSchema, 'user')

async function createUser(username) {
    return new User({
        username,
        created: Date.now()
    }).save()
}

async function findUser(username) {
    return await User.findOne({
        username
    })
}

;
(async() => {
    const connector = mongoose.connect(connectionString)
    const username = process.argv[2].split('=')[1]

    let user = await connector.then(async() => {
        return findUser(username)
    }).catch(console.log("Error found"))

    if (!user) {
        user = await createUser(username)
    }

    console.log(user)
    process.exit(0)
})()

但是下面的错误来了。我不知道出了什么问题。任何想法?

code error snippet here

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    试试这个命令

    sudo service mongod start
    

    然后nodemonnode app.js 启动服务器。

    【讨论】:

    • 由于我使用的是windows,所以我在以管理员身份运行时使用了CMD。还是没用。
    • 可能需要 2-3 分钟。发生火灾后,此命令会尝试运行服务器。
    • Mongodb 在本地系统中运行良好。我已经执行了多个命令。我还要重新安装吗?
    【解决方案2】:

    请检查您的连接字符串。您可以从 Mongo atlas 获取连接字符串。

    1. https://developerhandbook.com/mongodb/connect-mongo-atlas-mongoose/

    【讨论】:

    • 可能连接字符串有问题。有什么方法可以检查吗?
    • 您是否将您的 IP 列入白名单?
    • 是的。我已将 IP 地址列入白名单。我目前正在使用我的移动热点数据。应该没什么区别:/
    • 你创建了db用户吗?
    • 是的,我做到了。连接字符串也包含用户名和密码。
    【解决方案3】:
    const express = require('express');
    const bodyParser = require('body-parser');
    const mongoose = require('mongoose');
    const app = express();
    
    
    // Connecting to the database
    mongoose.connect('mongodb:uri',{ useNewUrlParser: true } ).then(() => {
        console.log("Successfully connected to the database");
    }).catch(err => {
        console.log('Could not connect to the database. Exiting now...');
        process.exit();
    });
    

    【讨论】:

      猜你喜欢
      • 2015-08-25
      • 1970-01-01
      • 2015-01-28
      • 1970-01-01
      • 2014-08-14
      • 2020-02-22
      • 2020-07-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多