Reputation: 1501
I am attempting to create a basic post on click in my NextJS app to a MongoDB database. The issue i am getting is TypeError: resolver is not a function
. I understand it might be a syncronicity issue but for the life of me I cannot figure out where.
Stack used: NextJS, Axios, Mongoose.
Component code snippet calling axios:
i know the states are updating so i am putting only the snippet that handles the request
handleSubmit = async (e: any) => {
e.preventDefault();
await axios
.post('/api/roomSession', {
roomName: this.state.roomName,
teamName: this.state.teamName
})
.then((response: any) => console.log('axios call reached', response))
.catch((error: any) => console.log('---- error! ----', error));
};
[...]
<button onClick={this.handleSubmit}>Create</button>
[...]
NextJS API file:
import { newSession } from '../../packages/backend/mongo/connection';
const apiNewSession = async (roomName, teamName) => {
await newSession(teamName, roomName);
};
export default apiNewSession();
Mongoose file:
const mongoose = require('mongoose');
mongoose
.connect(
'mongodbconnection',
{ useNewUrlParser: true, useUnifiedTopology: true }
)
.then(() => {
console.log('connected to mongoDB');
})
.catch(err => console.error('Connection failed: ', err));
const sessionSchema = new mongoose.Schema({
teamName: String,
roomName: String
});
const Session = mongoose.model.tests || mongoose.model('tests', sessionSchema);
export const newSession = async (teamName, roomName) => {
const session = new Session({
teamName,
roomName
});
const result = await session.save();
mongoose.connection.close();
};
Some extra info on the strange behaviour: When first time called, the code throws the aformentioned error but manages to reach the mongoDB connection and creates an EMPTY entry inside the collection (only _id, and _v). Upon second attempt, only the error is thrown.
Upvotes: 41
Views: 49118
Reputation: 1501
I was exporting the function incorrectly from the NextJS API file.
Correct method:
export default apiNewSession;
Not sure why it still happened when when i was exporting the function by default.
Upvotes: 92
Reputation: 11787
My problem was that I was defining a middleware function incorrectly...
This is okay
/* pages/api/endpoint.js */
export default MiddleWare(handler)
But middleware functions shouldn't be async
...
async function MiddleWare(handler) {
// ^ remove this!
return async function (req, res) {
// some async stuff
next(req, res);
}
}
Upvotes: 5