Last active
February 17, 2024 18:27
-
-
Save huynhsamha/4dcf00a1fba96ae7f186b606b33b7e9c to your computer and use it in GitHub Desktop.
How to create dynamic model with a schema in mongoose
This file contains 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
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')); |
This file contains 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
{ | |
"name": "test", | |
"version": "0.0.0", | |
"private": true, | |
"scripts": { | |
"start": "node app.js" | |
}, | |
"dependencies": { | |
"express": "~4.16.0", | |
"mongoose": "^5.4.0" | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.