0

I have an existing Node.js/Express app which connects to 2 separate databases, it has a MySQL DB for all the relational and a MongoDB store for the non-relational vertical data.

It uses Sequelize and Mongoose and works absolutely swimmingly.

I've been looking at Next.js today and I'm pretty impressed, one of my pet peeves with React is actually how much bootstrapping there is and how much code it takes to achieve something simple. Next.js seems to solve some of those issues for me, so I'm willing to embrace it.

First issue - Is it possible to connect Next.js to existing DB's and read their objects directly in the view?

e.g. ./server.js:

const mongoDb = mongoose.connect(configDB.url); // MongoDB connection
const models = require('./models'); // Sequelize connection

app.prepare().then(() => {
    server.use((req, res, next) => {
        req.mongodb = mongoDb
        req.mysqldb = models
        // Logging req.mysqldb/req.mongodb at this point gives the correct result.
        next()
    });

    server.get('*', (req, res) => {
        return handle(req, res)
    })
})

./pages/index.js:

Index.getInitialProps = async function(req) {
    console.log(req.mongodb);
    console.log(req.mysqldb)

    // Example of what I want: req.mysqldb.users.findAll()....... to populate collection for this view
}

When the console statements are executed in the index.js page, they are logged as undefined.

Ideally I want to use the objects/ORM layer directly in the next.js templates, I do not want to have to call my own API internally, it seems like a huge waste of resources!

Any help, greatly appreciated.

2 Answers 2

1

Just for future reference. getInitialProps gets passed in an object with one of the keys being req. So you're meant to do something like the following instead

// add the curly braces around req
Index.getInitialProps = async function({ req }) {
    // code
}

This is known as Function Parameter Destructuring and was introduced in ES6. What this accomplishes is similar to the following code

Index.getInitialProps = async function(_ref) {
    var req = _ref.req;
}

Meaning, it takes the value of req of the object that gets passed and uses that value.

Sign up to request clarification or add additional context in comments.

Comments

0

Well apparently by the time the request gets to the template it has changed a bit! Namely, it is nested within another request object.

req.req.mongodb and req.req.mysqldb both work fine :).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.