1

I have a node js application with many files. Three of them have the following declarations respectively:

mongoose2.connect("mongodb://localhost:27017/terms");
mongoose.connect("mongodb://localhost:27017/results");
mongoose.connect("mongodb://localhost:27017/users");

The problem is that this for some reason does not work. The data are saved in database, but mongoose is confused and each time they are saved randomly among terms, results and users. Do you know why this is happening and a workaround maybe ?

Cap Barracudas
  • 2,347
  • 4
  • 23
  • 54
  • Possible duplicate of [Mongoose and multiple database in single node.js project](https://stackoverflow.com/questions/19474712/mongoose-and-multiple-database-in-single-node-js-project) – Arif Khan Sep 24 '19 at 09:41
  • Make sure to read beyond the accepted answer on the linked answer, is [there is a better answer](https://stackoverflow.com/a/19475270/2579117) – Rogier Spieker Sep 24 '19 at 09:48

1 Answers1

1

Instead of creating 3 separate mongo connections it's better to switch between dbs using useDb() method.

const mongoose = require("mongoose");
const termsConn = mongoose.createConnection("mongodb://localhost:27017/terms");
//... code

const resultsConn = temmsConn.useDb("results");
console.log(resultsConn.name); // => results
nico
  • 176
  • 3