gpt4 book ai didi

node.js - mongoose 从 MongoDB (NodeJS/AWS Lambda) 检索空数组

转载 作者:太空宇宙 更新时间:2023-11-03 23:57:24 27 4
gpt4 key购买 nike

我正在 AWS Lambda 函数中使用 NodeJS 为 MongoDB Atlas 创建连接。我能够成功建立连接,但是当我执行 .find({}) 来获取所有数据时,我得到一个空数组。

Lambda

const mongoose = require('mongoose');

let conn = null;

const uri = 'mongodb+srv://xxx:xxx@todo-fnddg.mongodb.net/test';
let M = null;
exports.handler = async function(event, context) {
nodejs-aws-lambda-mongodb-atlas
context.callbackWaitsForEmptyEventLoop = false;
if (conn == null) {
conn = await mongoose.createConnection(uri, {
bufferCommands: false,
bufferMaxEntries: 0,
useNewUrlParser: true
});
M = conn.model('Todo', new mongoose.Schema(
{
title: String,
description: String,
date: Date,
status: String
}
));
}


const doc = M.find({});
console.log('items in the DB')
console.log(doc);

return null;
};

文档 Mongoose AWS Lambda: https://mongoosejs.com/docs/lambda.html

更新:

 M.find({}).exec().then(function(allDocs){
console.log('getting al docs')
console.log(allDocs)//[]
});

MongoDB Atlas

enter image description here

最佳答案

find是异步的,所以我认为你需要这样做:

M.find({}).exec().then(function(allDocs){
//do your thing
});

或者等待

let alldocs = await M.find({});

关于node.js - mongoose 从 MongoDB (NodeJS/AWS Lambda) 检索空数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56482277/

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