Extracting creation of a mongoose model out of server file

Kieran

New Member
#1
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
Mã:
app.post('/parser', (req, res) => { 
  var todo = new Todo({
    text: req.body.text,
  });
  todo.save().then((doc) => {
    res.send(doc);
  }, (e) => {
    res.status(400).send(e);
  })
});
Where my todo is just a mongoose model in a separate file
Mã:
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
 

Admin

Administrator
Thành viên BQT
#2
Change your database file to export a function which accepts the model name like this:
Mã:
module.exports = function(name) {
    var Todo = mongoose.model(name, {
        text: {
            type: String,
        }
    });
    return Todo;
}
Then your server.js import statement can look like:
Mã:
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.

Top