I’m testing Shopify’s next.js/koa setup and I want to connect to MongoDB and post some data.
I read this guide – https://dev.to/raphaelchaula/adding-mongodb-mongoose-to-next-js-apis-3af and did the same things, the difference is maybe I am using shopify’s boilerplate and there are things I cannot figure out.
The problem is that I am getting HTTP 405 – Method Not Allowed when I try to POST some data.
In server.js
I don’t have /cart route handler (I don’t know if I have to).
My middleware:
import mongoose from "mongoose";
const connectDB = (handler) => async (req, res) => {
if (mongoose.connections[0].readyState) {
// Use current db connection
return handler(req, res);
}
// Use new db connection
await mongoose.connect(process.env.mongoDBurl, {
useUnifiedTopology: true,
useFindAndModify: false,
useCreateIndex: true,
useNewUrlParser: true,
});
return handler(req, res);
};
export default connectDB;
My model (this is testing schema):
import mongoose from "mongoose";
var Schema = mongoose.Schema;
var cart = new Schema({
id: {
type: Number,
required: true,
},
store: {
type: String,
required: true,
},
createdAt: {
type: Date,
required: true,
},
});
mongoose.models = {};
var Cart = mongoose.model("Cart", cart);
export default Cart;
The /api/cart.js
route:
import connectDB from "../../middleware/mongodb";
import Cart from "../../models/cart";
const handler = async (req, res) => {
if (req.method === "POST") {
const { id, store, createdAt } = req.body;
if (id && store && createdAt) {
try {
// Hash password to store it in DB
var cart = new Cart({
id,
store,
createdAt,
});
// Create new cart
var cartcreated = await cart.save();
return res.status(200).send(cartcreated);
} catch (error) {
return res.status(500).send(error.message);
}
} else {
res.status(422).send("data_incomplete");
}
} else if (req.method === "GET") {
res.status(200).send("Success");
} else {
res.status(422).send("req_method_not_supported");
}
};
export default connectDB(handler);
My mondoDB url is inside next.config.js:
module.exports = {
webpack: (config) => {
const env = {
API_KEY: apiKey,
mongoDBurl:
"mongodb+srv://<username>:<password>@cluster0.wscad.mongodb.net/myFirstDatabase?retryWrites=true&w=majority",
};
config.plugins.push(new webpack.DefinePlugin(env));
// Add ESM support for .mjs files in webpack 4
config.module.rules.push({
test: /.mjs$/,
include: /node_modules/,
type: "javascript/auto",
});
return config;
},
};