D
D
de1m2017-03-30 10:49:25
Node.js
de1m, 2017-03-30 10:49:25

How to properly organize access to mongo db through socket.io?

I have a small nodejs and express.js page. The client communicates with the server through socket.io.

client.on('addLocation', function (location) {
    var locObj = JSON.parse(location);
    var db = mongoose.connection;

    db.on('error', function (error) {
      console.log(error);
    })

    db.once('open', function () {
      var collection = mongoose.model('esspunkts', essSchema);
      var dbEsspunkt = new collection({
        name: locObj.name,
        rating: {
          value: 0,
          rated: 0
        },
        addrr: {
          str: locObj.addr.str,
          plz: locObj.addr.plz,
          tel: locObj.addr.tel,
          mapurl: "http://maps.google.com/?q=" + locObj.addr.plz + " " + locObj.addr.ort + " , " + locObj.addr.str,
          menulink: locObj.menuurl
        }
      });

      dbEsspunkt.save(function (err, dbObj) {
        if (err) {
          console.log(err);
        } else {
          console.log("save successfull ", dbObj);
          mongoose.connection.close();
        }
      })
    })
    mongoose.connect(mongostr);
  })

That is, as you can see above, when the client accesses the server via socket.io, a new connection to mongodb is opened on the server side, and then closed again.
Actually the first question, is this generally correct? Or should I just open the connection at the beginning and just keep it open? How will it look like?
And the second question, as I understand it, is that if there are several users, then it is necessary to make a queue? What is the best way to do this?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
emp1re, 2017-03-30
@de1m

You need to open it once.

const mongoose = require('mongoose');

mongoose.Promise = global.Promise;
mongoose.connect("localhost:27017", function(err) {
  if (err) {
    console.log('MongoDB Connection Error:', err);
    process.exit(1);
  }
});

Create models separately. And so you get that it is created every time the event is called.
const mongoose = require('mongoose');
let dbEsspunkt = new mongoose.Schema({
    data: { type: any},
}, { timestamps: true });
dbEsspunkt.index(); // если нужно
var Esspunkt = mongoose.model('Esspunkt', dbEsspunkt);
module.exports = Esspunkt;

The queue will make the Event Loop for you, the question is how you build asynchrony.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question