我将我的NextJs
应用程序与MongoDB Atlas
连接。它在localhost上运行正常,但在Production hosted on Vercel
上不工作。
起初,我以为是网络访问的问题,添加了0.0.0.0/0 on the IP Access List
,但没有区别。错误500
只在产品上显示。
我已经从Formik的表单submit调用了nextjs的api。
连接和断开的代码
import mongoose from 'mongoose';
const connection = {};
async function connect() {
if (connection.isConnected) {
console.log('already connected');
return;
}
if (mongoose.connections.length > 0) {
connection.isConnected = mongoose.connections[0].readyState;
if (connection.isConnected === 1) {
console.log('use previous connection');
return;
}
await mongoose.disconnect();
}
const db = mongoose.connect(process.env.MONGODB_URI);
console.log('new connection');
connection.isConnected = db.connections[0].readyState;
}
async function disconnect() {
if (connection.isConnected) {
if (process.env.NODE_ENV === 'production') {
await mongoose.disconnect();
connection.isConnected = false;
} else {
console.log('not disconnected');
}
}
}
function convertDocToObj(doc) {
doc._id = doc._id.toString();
doc.createdAt = doc.createdAt.toString();
doc.updatedAt = doc.updatedAt.toString();
return doc;
}
const db = { connect, disconnect, convertDocToObj };
export default db;
人员模型
import mongoose from 'mongoose';
const PersonSchema = new mongoose.Schema(
{
name: { type: String, required: true },
count: { type: Number, required: false },
},
{
timestamps: true,
}
);
const Person = mongoose.models.Person || mongoose.model('Person', PersonSchema);
export default Person;
pages/api/my-endpoint.js
import db from '../../../mongoose/db';
import Person from '../../../mongoose/models/Person';
const handler = async (req, res) => {
// the codes
await db.connect();
let person = await Person.findOne({
name: 'Frank',
});
person.count += 1;
await type.save();
await db.disconnect();
// the codes
}
1条答案
按热度按时间mefy6pfw1#
我现在做的方式你们也可以尝试或修改--
/lib/dbConnect.js
/models/videos.js
/pages/api/getVideos.js
//api调用方法