MongoDB - Error: invalid schema, expected mongodb

前端 未结 9 2051
悲&欢浪女
悲&欢浪女 2020-12-13 05:59

I\'m new in building application with MEAN Stack, I\'m trying to build a real time chat app, here is my server side :

console.log(\"Server running...!\");

v         


        
相关标签:
9条回答
  • 2020-12-13 06:46

    I just had this issue as well and it was because I had the protocol wrong:

    mongo://localhost:27017/test
    

    The protocol being wrong can also cause this error. It should be like this:

    mongodb://localhost:27017/test
    
    0 讨论(0)
  • 2020-12-13 06:48

    Might seem obvious, but you'll also encounter this error when you pass invalid values in general to the mongo client, e.g. undefined. Ran into this when I was referencing the wrong key on a config object.

    0 讨论(0)
  • 2020-12-13 06:51

    Sometimes, error might be with the quotes around environment variables. Remove them once and try. Might help.

    Error might be with :

     set DATABASE_URI='mongodb://localhost:1000/my_app' && node index.js
    

    Correct command will be:

      set DATABASE_URI=mongodb://localhost:1000/my_app && node index.js
    
    0 讨论(0)
  • 2020-12-13 06:52

    Change content of this line from

    mongo.connect('localhost:27017/db/chat',function(err,db)
    

    to

    mongo.connect('mongodb://localhost:27017/db/chat',function(err,db)
    

    Then you can connect MongoDB database successfully.

    0 讨论(0)
  • 2020-12-13 06:54

    the working code would be like this

    don't forget to replace username, password & URL

    const socketClient = require('socket.io').listen(4000).sockets;
    const MongoClient = require('mongodb').MongoClient;
    
    const uri = "mongodb+srv://<username>:<password>@cluster0-saugt.mongodb.net/test?retryWrites=true&w=majority";
    
    const client = new MongoClient(uri, { useNewUrlParser: true });
    client.connect(err => {
        socketClient.on('connection', function (socket) {
    
            //Need to Get the Database first before trying to access the collections.
            let chat = client.db("test").collection('chats');
    
            // Get chats from mongo collection
            // perform actions on the collection object
            chat.find().limit(100).sort({ _id: 1 }).toArray(function (err, res) {
                if (err) {
                    throw err;
                }
    
                // Emit the messages
                socket.emit('output', res);
            });
    
    
        });
    
    });
    
    0 讨论(0)
  • 2020-12-13 06:54

    update your mongodb npm version

    0 讨论(0)
提交回复
热议问题