我正在尝试使用重新验证功能。我尝试按照 Vercel 提供的代码进行操作,但我不断收到错误消息。这是我正在使用的功能:
export async function getServerSideProps() {
const client = await clientPromise;
const db = client.db("myFirstDatabase");
let users = await db.collection("users").find({}).toArray();
users = JSON.parse(JSON.stringify(users));
return {
props: {
users,
},
revalidate: 15,
};
}
这是返回客户端的 mongodb 文件:
import { MongoClient } from 'mongodb'
const uri = process.env.MONGODB_URI
const options = {
useUnifiedTopology: true,
useNewUrlParser: true,
}
let client
let clientPromise
if (!process.env.MONGODB_URI) {
throw new Error('Please add your Mongo URI to .env.local')
}
if (process.env.NODE_ENV === 'development') {
// In development mode, use a global variable so that the value
// is preserved across module reloads caused by HMR (Hot Module Replacement).
if (!global._mongoClientPromise) {
client = new MongoClient(uri, options)
global._mongoClientPromise = client.connect()
}
clientPromise = global._mongoClientPromise
} else {
// In production mode, it's best to not use a global variable.
client = new MongoClient(uri, options)
clientPromise = client.connect()
}
export default clientPromise
如果我删除重新验证部分,我已经能够连接到数据库并且代码可以正常工作。我得到的错误是:
** 错误:从 . 返回了其他键getServerSideProps
。用于您的组件的属性必须嵌套在props
键下,例如:
return { props: { title: 'My Title', content: '...' } }
需要移动的键:重新验证。阅读更多:https ://nextjs.org/docs/messages/invalid-getstaticprops-value
**
我不确定我做错了什么。我想从数据库中获取数据并每 15 秒更新一次。任何帮助将不胜感激。