MongoDB Atlas错误:无效的架构,预期的mongodb [英] MongoDB Atlas error: invalid schema, expected mongodb

查看:71
本文介绍了MongoDB Atlas错误:无效的架构,预期的mongodb的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在遍历 Hello World应用程序教程在GCP中.而且我陷入了server.js步骤.

I am running through the Hello World app tutorial in GCP. And I am getting stuck at the server.js step.

server.js的代码如下:

The code of the server.js is as below:

'use strict';

const mongodb = require('mongodb');
const http = require('http');
const nconf = require('nconf');
let uri = 'mongodb+srv://my_name:<mypassword>@mydatabase-clr75.gcp.mongodb.net/test?retryWrites=true&w=majority';
if (nconf.get('mongoDatabase')) {
  uri = `${uri}/${nconf.get('mongoDatabase')}`;
}
console.log(uri);

mongodb.MongoClient.connect(uri, (err, db) => {
  if (err) {
    throw err;
  }

  // Create a simple little server.
  http.createServer((req, res) => {
    if (req.url === '/_ah/health') {
      res.writeHead(200, {
        'Content-Type': 'text/plain'
      });
      res.write('OK');
      res.end();
      return;
    }

    const collection = db.collection('Messages');
    var datetime = new Date();
    const msg = {
      msgDescription: '\nHello World received on ' + datetime
    };

    collection.insert(msg, (err) => {
      if (err) {
        throw err;
      }

      // push out a range
      let msglist = '';
      collection.find().toArray((err, data) => {
        if (err) {
          throw err;
        }
        data.forEach((msg) => {
          msglist += `${msg.msgDescription}; `;
        });

        res.writeHead(200, {
          'Content-Type': 'text/plain'
        });
res.write('Messages received so far:\n');
        res.end(msglist);
      });
    });
  }).listen(process.env.PORT || 8080, () => {
    console.log('started web process');
  });
});

我收到如下错误:

mongodb + srv://my_name:@ mydatabase-clr75.gcp.mongodb.net/test?retryWrites = true& w = majority/home/herboratory/node_modules/mongodb/lib/url_parser.js:19抛出新的错误('无效的架构,预期的mongodb');^错误:无效的架构,预期的mongodb在module.exports(/home/herboratory/node_modules/mongodb/lib/url_parser.js:19:11)在连接时(/home/herboratory/node_modules/mongodb/lib/mongo_client.js:486:16)在Function.MongoClient.connect(/home/herboratory/node_modules/mongodb/lib/mongo_client.js:250:3)在对象.(/home/herboratory/server.js:12:21)在Module._compile(module.js:653:30)在Object.Module._extensions..js(module.js:664:10)在Module.load(module.js:566:32)在tryModuleLoad(module.js:506:12)在Function.Module._load(module.js:498:3)在Function.Module.runMain(module.js:694:10)npm ERR!代码ELIFECYCLE npm ERR!errno 1 npm错误!test@1.0.0开始: nodeserver.js npm错误!退出状态1 npm ERR!npm ERR!失败于test@1.0.0启动脚本.npm ERR!这可能不是问题npm.上面可能还有其他日志记录输出.npm ERR!一种此运行的完整日志可以在以下位置找到:npm ERR!
/home/herboratory/.npm/_logs/2019-06-26T03_58_26_823Z-debug.log

mongodb+srv://my_name:@mydatabase-clr75.gcp.mongodb.net/test?retryWrites=true&w=majority /home/herboratory/node_modules/mongodb/lib/url_parser.js:19 throw new Error('invalid schema, expected mongodb'); ^ Error: invalid schema, expected mongodb at module.exports (/home/herboratory/node_modules/mongodb/lib/url_parser.js:19:11) at connect (/home/herboratory/node_modules/mongodb/lib/mongo_client.js:486:16) at Function.MongoClient.connect (/home/herboratory/node_modules/mongodb/lib/mongo_client.js:250:3) at Object. (/home/herboratory/server.js:12:21) at Module._compile (module.js:653:30) at Object.Module._extensions..js (module.js:664:10) at Module.load (module.js:566:32) at tryModuleLoad (module.js:506:12) at Function.Module._load (module.js:498:3) at Function.Module.runMain (module.js:694:10) npm ERR! code ELIFECYCLE npm ERR! errno 1 npm ERR! test@1.0.0 start: node server.js npm ERR! Exit status 1 npm ERR! npm ERR! Failed at the test@1.0.0 start script. npm ERR! This is probably not a problem with npm. There is likely additional logging output above. npm ERR! A complete log of this run can be found in: npm ERR!
/home/herboratory/.npm/_logs/2019-06-26T03_58_26_823Z-debug.log

我想知道这里是在读取同一错误行的其他文章后出现格式错误,所以我尝试了'...',"...",并且不带引号,但仍然保持错误.请指导我哪里出了问题?

I was wondering it should be the format error after reading some other posts here with the same error line, so I've tried '...', "..." and without any quotation mark but still remain error. Would please guide me where's the error?

除了URI之外,我还需要在代码内部进行其他任何修改吗?据我所知,我只需要插入自己的Atlas Connection字符串即可.

Except for the URI, is there anywhere else I also need to modify inside the code? As far as I know from the instruction I just need to insert my own Atlas Connection string.

非常感谢.

推荐答案

我有相同的错误.问题在于mongoDB Atlas中的设置和我的应用程序中的设置.

I had the same error. The problem was with setup in mongoDB Atlas and setup in my Application.

在mongoDB Atlas中:

  • 创建数据库并进行收集
  • 创建数据库用户
  • 在"IP白名单",网络访问"中添加您的IP地址(公共)

我的解决方案示例:

文件.env

MONGO_URI=mongodb+srv://jmendoza:your-password@cluster0-7rxkw.mongodb.net/nodeapi?retryWrites=true&w=majority
PORT=3000

文件app.js

const express = require('express');
const morgan = require('morgan');
const dotenv = require('dotenv');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const expressValidator = require('express-validator');
const { postRoutes } = require('./routes/posts');

const app = express();
const port = process.env.PORT || 3000;

dotenv.config();

// BD
mongoose.connect(process.env.MONGO_URI, { useNewUrlParser: true, useUnifiedTopology: true })
    .then(() => console.log('mongoDB, Atlas. Connected'))
    .catch((err) => console.error(err));

// Middleware
app.use(morgan('dev'));
app.use(bodyParser.json());
app.use(expressValidator());

// Routes
app.use('/api/v1', postRoutes);

app.listen(port, () => {
    console.log(`A NodeJS API is listining on port: ${port}`);
});

文件package.json

File package.json

{
    "name": "node-api",
    "version": "1.0.0",
    "description": "A NodeJS API",
    "main": "app.js",
    "scripts": {
        "dev": "nodemon app.js"
    },
    "keywords": [
        "node",
        "api"
    ],
    "author": "Jonathan Mendoza",
    "license": "ISC",
    "dependencies": {
        "body-parser": "^1.19.0",
        "dotenv": "^8.2.0",
        "express": "^4.17.1",
        "express-validator": "^5.3.1",
        "mongoose": "^5.9.7",
        "morgan": "^1.9.1",
        "nodemon": "^2.0.3"
    }
}

正在运行的应用程序(控制台)

Running application (console)

jmendoza@jmendoza-ThinkPad-T420:~/IdeaProjects/NodeJS-API-Course/Basic-Node-API$ npm run dev

> node-api@1.0.0 dev /home/jmendoza/IdeaProjects/NodeJS-API-Course/Basic-Node-API
> nodemon app.js

[nodemon] 2.0.3
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,json
[nodemon] starting `node app.js`
A NodeJS API is listining on port: 3000
mongoDB, Atlas. Connected

NodeJS版本

jmendoza@jmendoza-ThinkPad-T420:~/IdeaProjects/NodeJS-API-Course/Basic-Node-API$ node -v
v13.12.0

您可以在GitHub上看到我的完整代码:

You can see my full code on GitHub:

https://github.com/JonathanM2ndoza/NodeJS-API-Course/tree/master/Basic-Node-API

这篇关于MongoDB Atlas错误:无效的架构,预期的mongodb的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆