gpt4 book ai didi

node.js - MongoDB Mongoose 错误: Cannot call `collection.aggregate()` before initial connection is complete

转载 作者:行者123 更新时间:2023-12-05 09:29:24 27 4
gpt4 key购买 nike

My websiteNextJS build (并由 Vercel 托管)在我的 NodeJS API 中使用 Mongoose 连接到我的 MongoDB 数据库。

只有大约 1% 的用户遇到了这个奇怪的错误:

MongooseError: Cannot call `hotels.aggregate()` before initial connection is complete if `bufferCommands = false`. Make sure you `await mongoose.connect()` if you have `bufferCommands = false`.
at NativeCollection.<computed> [as aggregate] (/var/task/node_modules/mongoose/lib/drivers/node-mongodb-native/collection.js:193:15)
at /var/task/node_modules/mongoose/lib/aggregate.js:998:18
at /var/task/node_modules/kareem/index.js:23:7
at processTicksAndRejections (internal/process/task_queues.js:77:11)

(hotels 是正在显示的集合,我正在我的 API 中调用 .aggregate() 函数)

我无法可靠地重现错误,但它也发生在我身上。

我正在按照 NextJS 推荐的方式连接到 MonogoDB from their example :

import mongoose from 'mongoose'

const MONGODB_URI = process.env.MONGODB_URI

if (!MONGODB_URI) {
throw new Error(
'Please define the MONGODB_URI environment variable inside .env.local'
)
}

/**
* Global is used here to maintain a cached connection across hot reloads
* in development. This prevents connections growing exponentially
* during API Route usage.
*/
let cached = global.mongoose

if (!cached) {
cached = global.mongoose = { conn: null, promise: null }
}

async function dbConnect() {
if (cached.conn) {
return cached.conn
}

if (!cached.promise) {
const opts = {
bufferCommands: false,
}

cached.promise = mongoose.connect(MONGODB_URI, opts).then((mongoose) => {
return mongoose
})
}
cached.conn = await cached.promise
return cached.conn
}

export default dbConnect

与错误消息相反,我正在等待 mongoose.connect()。我的 API 是这样开始的:

import dbConnect from "utils/dbConnect";
import HotelModel from "models/HotelModel";

export default async function handler(req, res) {
await dbConnect();

try {
const pipeline = {}; // this is a big aggregation pipeline

const hotels = await HotelModel.aggregate(pipeline);

return res.status(200).json(hotels);
} catch{
...
}
}

有人知道为什么会发生这种情况吗?

最佳答案

移除

const opts = {
bufferCommands: false,
}

或明确设置 bufferCommands: true

Vercel 在 AWS Lambda 上运行,有时它会导致缓存连接出现问题。 Vercel 的一位贡献者提示 mongoose 中的相应 PR https://github.com/Automattic/mongoose/issues/9239#issuecomment-659000910

他们建议避免在线程中使用 bufferCommands: false 并在一年后将其从官方 Mongoose 建议中删除:docs/lambda.md

关于node.js - MongoDB Mongoose 错误: Cannot call `collection.aggregate()` before initial connection is complete,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70692250/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com