Skip to content

Instantly share code, notes, and snippets.

@ganeshkbhat
Last active September 19, 2022 07:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ganeshkbhat/f284ad9d3d2deb890c94c14b39452d2e to your computer and use it in GitHub Desktop.
Save ganeshkbhat/f284ad9d3d2deb890c94c14b39452d2e to your computer and use it in GitHub Desktop.
ExpressJS: API Template for getter from Database
/**
* Route Template: Config
* Path: ./expressjs.api.config.js
*/
var config = {
"pathRoute": "/main",
"dbConfig": {
"path": "mongodb://localhost:27017/test",
"conf": {
"useNewUrlParser": true,
"useUnifiedTopology": true,
"useCreateIndex": true,
"useFindAndModify": false
}
},
"someOtherConfig": ""
};
module.exports = config;
/**
* Mongoose MongoDB Model: Mongoose Users Model
* Path: ./expressjs.api.models.js
*/
var mongoose = require("mongoose");
var config = require("../expressjs.api.config");
var dbconn = null;
function getDBInstance() {
try {
if (dbconn != null) { return dbconn; }
else {
dbconn = mongoose.connect(config.dbConfig.path, config.dbConfig.conf).catch(error => { console.log(error) });
return dbconn;
}
} catch (e) {
return e;
}
}
getDBInstance();
mongoose.connection.on('error', err => { console.log(err); });
const UsersSchema = new mongoose.Schema(
{ type: { type: String, enum: ['employee', 'intern'], required: true }, username: { type: String, required: true } },
{ collection: 'users' }
)
UsersSchema.index({ slug: 1, userid: 1 }, { unique: true });
const usermodel = dbconn.model('Users', UsersSchema);
await usermodel.createCollection();
module.exports = {
"users": usermodel,
"conn": getDBInstance()
}
/**
* Route Template: API Get Request
* Path: ./templates/expressjs.routes.get.template.js
*/
function getRequest(req, res, next) {
const Schema = require("./expressjs.api.models.js")["users"];
var response = await Schema.find();
res.send(response);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment