gpt4 book ai didi

javascript - 从 mongodb connect 和 find 返回一个数组

转载 作者:可可西里 更新时间:2023-11-01 10:14:26 26 4
gpt4 key购买 nike

我有以下代码用于连接到我的 MongoDB 实例并返回一些记录。我需要遍历游标结果来为我的应用程序创建合适的数据结构。但是,我努力弄清楚如何将表数组的内容返回给调用函数。如果我预定义一个表变量,它就可以工作,但这不是我需要实现的。

如何让 findUsage 函数将表数组返回给调用 MongoClient.connect 代码?

const MongoClient = require('mongodb').MongoClient
const assert = require('assert')
const url = 'mongodb://localhost:27017/test'

const table = []
const findUsage = function (db, callback) {
const cursor = db.collection('usage')
.find({ },
{'customer': 1})
cursor.each(function (err, doc) {
assert.equal(err, null)
if (doc != null) {
table.push(
[doc.customer]
)
} else {
callback(table)
}
})
}

MongoClient.connect(url, function (err, db) {
assert.equal(null, err)
findUsage(db, function () {
// console.log("Session: %j", table);
console.log(table)
db.close()
})
})

最佳答案

使用方法toArray处理查找光标。然后使用回调,无论是否有数据。

        const findUsage = function (db, callback) {
const cursor = db.collection('usage')
.find({}, {
'customer': 1,
});

cursor.toArray(function (err, docs) {
assert.equal(err, null);

if (docs) {
return callback(docs.map(x => x.customer));
}

return callback([]);
});
}

MongoClient.connect(url, function (err, db) {
assert.equal(null, err);

findUsage(db, function (docs) {
// ...

db.close();
});
});

关于javascript - 从 mongodb connect 和 find 返回一个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46468226/

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