首页 > 解决方案 > 无法连接到 MongoDB 并通过 Node / Postman 创建新的 Collections 文件夹

问题描述

我正在关注这个 Youtube 视频的教程,以便构建一个可以与我的 Mongo 数据库连接和交互的 API。在我到达链接中引用的部分(1:05:20)之前,进展非常顺利。

这是教程创建者使用的代码。

let mongoose = require('mongoose')
const server = 'ds221609.mlab.com:21609'
const database = 'rest-api-workshop'
const user = 'username'
const password = 'password'

mongoose.connect(`mongodb://${user}:${password}@${server}/${database}`)

let CustomerSchema = new mongoose.Schema({
  name: String,
  email: {
    type: String,
    requried: true,
    unique: true
  }
})

module.exports = mongoose.model('Customer', CustomerSchema)

我显然用我的 mongodb 用户的凭据交换了凭据,但仍然无法让它工作。此外,mongodb 给出的格式现在看起来非常不同:

const MongoClient = require('mongodb').MongoClient;
const uri = "mongodb+srv://<username>:<password>@<databaseID>.azure.mongodb.net/admin?retryWrites=true&w=majority";
const client = new MongoClient(uri, { useNewUrlParser: true });
client.connect(err => {
  const collection = client.db("test").collection("devices");
  // perform actions on the collection object
  client.close();
});

我的目标是基本上在我的数据库集合的“客户”文件夹下创建一个新记录。我如何在 2019 年实现这一目标?

标签: node.jsmongodb

解决方案


推荐阅读