MongoDB - Error: invalid schema, expected mongodb

前端 未结 9 2127
悲&欢浪女
悲&欢浪女 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: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://:@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);
            });
    
    
        });
    
    });
    

提交回复
热议问题