发芽错误db.collection不是函数吗?

时间:2018-10-27 09:50:06

标签: javascript node.js mongodb

我在mongodb中使用socket.io和nodejs / express。在server.js中,我将数据存储在mongodb中,但出现错误db.collection不是一个函数,为什么呢?

我已经看到了这个问题-> db.collection is not a function when using MongoClient v3.0,但是我不明白如何修改我的代码才能使其正常工作?我应该将所有代码移到.then()内吗?

代码:

server.js:

const express = require('express');
const mongoose = require('mongoose');
const socket = require('socket.io');
const message = require('./model/message')

const app = express();

const db = require('./config/keys').mongoURI;

mongoose.connect(db, {useNewUrlParser: true})
  .then(() => console.log('Mongodb connected...'))
  .catch( err => console.log(err));

const port = 5000;

let server = app.listen(5000, function(){
  console.log('server is running on port 5000')
});

let io =  socket(server);

io.on("connection", function(socket){
  console.log("Socket Connection Established with ID :"+ socket.id)

  socket.on('disconnect', function(){
    console.log('User Disconnected');
  });

  let chat = db.collection('chat');  <---GETTING ERROR HERE

      socket.on('SEND_MESSAGE', function(data){
        let message = data.message;
        let date = data.date;

        // Check for name and message
        if(name !== '' || date !== ''){
            // Insert message
            chat.insert({message: message, date:date}, function(){
                socket.emit('output', [data]);
            });
        }
    });

    chat.find().limit(100).sort({_id:1}).toArray(function(err, res){
      if(err){
          throw err;
      }
      // Emit the messages
      socket.emit('RECEIVE_MESSAGE', res);
    });

})

注意:我的mongo版本是4

2 个答案:

答案 0 :(得分:1)

您需要像下面那样将连接传递给数据库对象

const mongoURI = require('./config/keys').mongoURI;

mongoose.connect(mongoURI, {useNewUrlParser: true}

db = mongoose.connection;

db.on('error', console.error.bind(console, 'connection error:'));

db.once('open', function() {
console.log('Mongodb connected...')
});

此后,您就可以使用db对象了。然后,您创建schmeamodels并使用它来插入或查询数据。在您的情况下,它是chat模型。

似乎您对mongoose的用法尚不清楚,所以我建议您先阅读文档:https://mongoosejs.com/docs/index.html

答案 1 :(得分:0)

尝试

const url = "mongodb://<dbuser>:<dbpassword>@ds141633.mlab.com:41633/mongochat";
const options = const options = {

  useNewUrlParser: true,

  autoIndex: false, // Don't build indexes

  reconnectTries: Number.MAX_VALUE, // Never stop trying to reconnect

  reconnectInterval: 1000, // Reconnect every 500ms

  poolSize: 10, // Maintain up to 10 socket connections

  // If not connected, return errors immediately rather than waiting for reconnect
  bufferMaxEntries: 0,

  connectTimeoutMS: 10000, // Give up initial connection after 10 seconds

  socketTimeoutMS: 45000, // Close sockets after 45 seconds of inactivity
  family: 4 // Use IPv4, skip trying IPv6

};

//与数据库的连接...

**

mongoose.connect(url, options).then(
  () => {
    console.log('database connected');
  },
  err => console.log(err)
);
mongoose.Promise = global.Promise;

**