【问题标题】:Unable to connect to my database from my node js application无法从我的节点 js 应用程序连接到我的数据库
【发布时间】:2021-12-10 12:46:40
【问题描述】:

我一直在尝试将我的应用程序连接到我的数据库,但这一直是不可能的。我在下面尝试过,但它仍然无法识别我的模型

const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');

// Connection URL
const url = process.env.MONGODB_URL;

// Database Name
const dbName = 'KaydeeAcedemy';

// Use connect method to connect to the server
MongoClient.connect(url, { useNewUrlParser: true, useUnifiedTopology: true }, function(err, client) {
    assert.equal(null, err);
    console.log("Connected successfully to server");

    const db = client.db(dbName);

    client.close();
});

我也尝试过使用这个连接字符串,但没有进展。

const { MongoClient } = require('mongodb');
const uri = process.env.MONGODB_URL;
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
client.connect(err => {
    const collection = client.db("test").collection("devices");
    // perform actions on the collection object
    client.close();
  });

当我尝试从我的应用程序中添加新用户时,由于数据库而出现此错误。

Operation `users.findOne()` buffering timed out after 10000ms

mongodb url 如下所示:

MONGODB_URL = mongodb+srv://Kaydeeacademy:**************@cluster0.ehclf.mongodb.net/KaydeeAcademy?retryWrites=true&w=majority

我不知道我是否遗漏了连接字符串中的某些内容或某处。

【问题讨论】:

    标签: javascript node.js mongodb


    【解决方案1】:

    你能测试/比较我的一些代码(工作)

    // have you called in the dot.env file?
    require('dotenv').config()
    const express = require('express')
    const mongoose = require('mongoose')
    
    
    // don't include the "useNewUrlParser: true, useUnifiedTopology: true" see answer below:
    // https://stackoverflow.com/questions/68915722/option-usefindandmodify-is-not-supported
    
    
    // make sure there are no spaces in the dot.env file
    mongoose.connect(process.env.MONGO_URI)
      .then(() => console.log("db connected!"))
      .catch(err => console.error("db connection failed ", err))
    

    【讨论】:

      猜你喜欢
      • 2022-11-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-29
      • 2019-11-08
      • 2020-12-05
      相关资源
      最近更新 更多