Skip to content

Instantly share code, notes, and snippets.

@puuble
Last active January 30, 2023 15:14
Show Gist options
  • Save puuble/c78c7446bdfc212cefa61331825ae477 to your computer and use it in GitHub Desktop.
Save puuble/c78c7446bdfc212cefa61331825ae477 to your computer and use it in GitHub Desktop.
multiple database structure by schema
//database/config.js
const mongoose = require('mongoose');
class Database {
constructor(options) {
this.options = options;
this.connect();
}
connect() {
//Create the DSN address And Connect to the database
mongoose.connect(this.options.dsn, {
useNewUrlParser: true,
useUnifiedTopology: true
});
}
}
module.exports = Database;
//models/user.js
const mongoose = require('mongoose');
const Database = require('../database/config');
class User extends Database {
constructor(options) {
super(options);
this.schema = new mongoose.Schema({
name: String,
email: String
});
this.model = mongoose.model('User', this.schema);
}
create(data) {
// Create a new user
const user = new this.model(data);
return user.save();
}
find(query) {
// Find users that match the query
return this.model.find(query);
}
}
module.exports = User;
//test for express js you need to add this line in the router/index.js
const user = new User({
dsn: 'MONGO_URL' // this url can be come from session or cookie or environment. This is how to dynamically change dsn by schema
});
//
//DSN
//PROJECT
router.post('/create', (req, res) => {
user.dsn = req.dsn
projectFolder = "MM"
const User = require('../models/'+projectFolder+'/config');
user
.create(req.body)
.then((data) => {
res.json(data);
})
.catch((err) => {
res.json(err);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment