在将mongoDB与node.j连接时出现Mongoose连接问题

时间:2019-12-16 16:59:01

标签: node.js mongodb mongoose socket.io

这是我的节点服务器代码。有一个出价应用程序,例如带有mongoDB,node.js,socket.io和Angular的在线拍卖行。我现在可以通过套接字与前端通信,但是我无法将任何数据保存到mongoDB或无法从那里获取数据。这段代码在6个月前就可以正常工作了。但这不是现在。原始代码在我的github中,其链接为:https://github.com/bbketen/Live-Auction-House

let app = require("express")();
let http = require("http").Server(app);
let io = require("socket.io")(http);
let mongoose = require('mongoose');

mongoose.connect('mongodb://localhost:27017/AuctionHouse', (err) => {
  if(err){
    console.log("error" + err);
  } else{
    console.log("mongodb connected");
  }
})

let schema = mongoose.Schema;


let Auction = new schema({
  bids:{
    name:String,
    bid:Number,
    bidDate:Date
  },
  deadLine:Date
})
const id = mongoose.Types.ObjectId("5dee9ff2c7c853390003d1c1");

let clients = [];


let bidModel = mongoose.model('auction', Auction);
//let ObjectId = mongoose.Types.ObjectId;

io.on("connection", socket =>{
  console.log("User connected");
  clients.push(socket.id);

  if(clients != []){
    for(let i = 0; i< clients.length; i++){
      if(io.sockets.connected[clients[i]] != undefined){
        io.sockets.connected[clients[i]].emit("user", "User" + (i + 1));
      }
    }
  }


  socket.on("disconnect", function() {
    console.log("user disconnected");
    io.emit("user", "User" + Object.keys(io.sockets.connected).length);
  });

  socket.on("find", function(msg){
    bidModel.aggregate([ // datanın tamamını almayı sağlar
      { $unwind: '$bids'},
      { $sort: {
        "bids.bid" : -1
      }},
      { $limit : 2}
    ], function(err,msg){
      if(err){
        console.log(err);
      } else{
        io.emit("found", msg);
        console.log(msg);
      }
    })
  })

  socket.on("insert", function(msg){
    console.log("bos mu:");
    console.log(msg.bids);
    bidModel.findOneAndUpdate({_id:id}, {
      $push: {
        bids:msg.bids
      }
    }, {new:true} ,function(err,msg){
      if(err){
        console.log(err);
      } else{
        console.log(msg);
      }
    })
  })

  socket.on("delete", function(){
    bidModel.findOneAndUpdate({_id:id}, {
      $unset: {
        bids:[]
      }
    }, function(err){
      if(err){
        console.log(err);
      } else{
        io.emit("deleted", "deleted")
      }
    })
  })
})

http.listen(5000, () => {
  console.log("started on port 5000");
});

预先感谢您的回答。

0 个答案:

没有答案