Extracting creation of a mongoose model out of server file


New Member
I'm currently building a generic express API and I'm finding it difficult to extract code from my server.js file

I have the following in my server.js file
app.post('/parser', (req, res) => { 
  var todo = new Todo({
    text: req.body.text,
  todo.save().then((doc) => {
  }, (e) => {
Where my todo is just a mongoose model in a separate file
var Todo = mongoose.model('Hello123', {
    text: {
        type: String,

module.exports = { Todo };
I want to pass any string from my server file as a variable for my database name, so in this case pass any variable where I have 'Hello123'

Is it possible to do this? I've been trying to export the creation of the model as function and call this from the server file however this hasn't worked

Not the end of the world if I can't however I like keeping all functionality etc. out of my server.js file such that it is easier to read


Thành viên BQT
Change your database file to export a function which accepts the model name like this:
module.exports = function(name) {
    var Todo = mongoose.model(name, {
        text: {
            type: String,
    return Todo;
Then your server.js import statement can look like:
var modelName = 'Hello123';
var Todo = require('./database.js')(modelName);
This should work.

Từ khóa phổ biến

You are using an out of date browser. It may not display this or other websites correctly.
You should upgrade or use an alternative browser.

Chủ Đề Xem Nhiều