Last active
January 30, 2023 15:14
-
-
Save puuble/c78c7446bdfc212cefa61331825ae477 to your computer and use it in GitHub Desktop.
multiple database structure by schema
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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