Skip to content

Instantly share code, notes, and snippets.

@huynhsamha
Last active February 17, 2024 18:27
Show Gist options
  • Save huynhsamha/4dcf00a1fba96ae7f186b606b33b7e9c to your computer and use it in GitHub Desktop.
Save huynhsamha/4dcf00a1fba96ae7f186b606b33b7e9c to your computer and use it in GitHub Desktop.
How to create dynamic model with a schema in mongoose
const http = require('http');
const express = require('express');
const mongoose = require('mongoose');
const app = express();
const server = http.Server(app);
const connectionUri = 'mongodb://localhost/dbtest';
mongoose
.connect(connectionUri, { useNewUrlParser: true })
.then(() => {
console.log('Connection to database established');
})
.catch(err => {
console.log(err);
process.exit(-1);
});
const Schema = mongoose.Schema;
const UserInfoSchema = new Schema({
note: String,
timeline: { type: Date, default: Date.now }
});
app.get('/add/:id/:note', async (req, res) => {
const { id, note } = req.params;
// Retrieve model which contain info documents of user with id
const UserInfo = mongoose.model('User_' + id, UserInfoSchema);
const log = new UserInfo({ note });
await log.save();
res.send(log);
})
app.get('/:id', async (req, res) => {
const { id } = req.params;
// Retrieve model which contain info documents of user with id
const UserInfo = mongoose.model('User_' + id, UserInfoSchema);
const logs = await UserInfo.find();
res.send(logs);
})
server.listen('8080', () => console.log('Listening on 8080'));
{
"name": "test",
"version": "0.0.0",
"private": true,
"scripts": {
"start": "node app.js"
},
"dependencies": {
"express": "~4.16.0",
"mongoose": "^5.4.0"
}
}
@Shaiq1217
Copy link

I am trying to do something similar, but when my server restarts and I try to fetch again the data, it says the schema is not registered.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment