简体   繁体   中英

MongoDB Atlas error: invalid schema, expected mongodb

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

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');
  });
});

I receive the error as below:

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?

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.

Many thanks.

The error invalid schema, expected mongodb means that you're using an outdated node driver version. The old driver cannot parse the new mongodb+srv URI scheme.

Support for the mongodb+srv scheme was added in the node driver version 3.0 in this ticket: NODE-1145 .

Upgrade your node driver using:

$ npm install mongodb

and the error should go away.

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

In mongoDB Atlas:

  • Create DATABASE and COLLECTION
  • Create Database User
  • Add your IP Address (public) in IP Whitelist, Network Access

Example of my solution:

File .env

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

File 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}`);
});

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 Version

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

You can see my full code on GitHub:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM