gpt4 book ai didi

node.js - 获取 mongodb 数据到 nodejs 数组?

转载 作者:IT老高 更新时间:2023-10-28 13:33:22 25 4
gpt4 key购买 nike

我在将 mongodb 数据导入 nodejs 数组时遇到问题,如下所示:

测试数据库:

{
"supportTicket" : "viT8B4KsRI7cJF2P2TS7Pd0mfqaI5rtwf",
"msgId" : 1379304604708.0,
"username" : "Guest-OSsL2R",
"message" : "hello",
"_id" : ObjectId("5236849c3651b78416000001")
}

Nodejs:

function _getMsg(st, callback) {
db.test.find({ supportTicket: st }).toArray(function (err, docs) {
callback(docs);
});
}

var nodeArr = _getMsg('viT8B4KsRI7cJF2P2TS7Pd0mfqaI5rtwf', function (res) {
console.log(res); // --> res contain data and printed ok
return res;
});

console.log('return data: ' + nodeArr ) // --> However, nodeArr is undefined.

结果如下:

return data: undefined
return data: undefined
[ { supportTicket: 'viT8B4KsRI7cJF2P2TS7Pd0mfqaI5rtwf',
msgId: 1379304604708,
username: 'Guest-OSsL2R',
message: 'dhfksjdhfkj',
_id: 5236849c3651b78416000001 } ]
[ { supportTicket: 'viT8B4KsRI7cJF2P2TS7Pd0mfqaI5rtwf',
msgId: 1379304604708,
username: 'Guest-OSsL2R',
message: 'dhfksjdhfkj',
_id: 5236849c3651b78416000001 } ]

问题是:如何从测试数据库中获取数据并将数据分配给nodeArr?

最佳答案

如您所见,控制台确实显示了 _getMsg 调用的结果。

_getMsg 不返回值,因此当您尝试将 nodeArr 变量分配给结果时,它会获取 undefined 的值> 因为没有 return 值。即使您将其更改为返回值,在调用函数时,结果也没有返回。

find 的调用与许多 NodeJ 和 MongoDb 驱动程序一样是异步的。因此,它不会立即返回,这就是为什么您需要回调在函数完成时发出信号的原因。如果没有这种模式,函数调用者将永远不会收到结果。

你在回调中定义了一个返回值:return res。这会将结果返回给发起调用的函数:callback(docs)。虽然从技术上讲它没有任何问题,但没有理由这样做,因为调用者已经有了结果。这只是忙碌的工作。

此外,在 NodeJS 的全局范围内声明变量时,我会非常小心。对于异步行为(并且只有一个线程完成所有连接的所有工作),您可能会发现在任何给定时刻如果不检查就很难确定全局变量的值。

function _getMsg(st, callback) {
db.test.find({ supportTicket: st }).toArray(function (err, docs) {
callback(docs);
});
}

_getMsg('viT8B4KsRI7cJF2P2TS7Pd0mfqaI5rtwf', function (res) {
console.log(res); // --> res contain data and printed ok
var nodeArr = res; // just moved the nodeArr declaration to function scope
// *** do next step here, like send results to client
});

如果您将结果发送回客户端,在对 _getMsg 的调用中,您可能会遇到这样的情况(假设它是在处理 http request) :

response.writeHead(200, { 'Content-Type': 'application/json'});
response.write(JSON.stringify(nodeArr));
response.end();

这本可以包含在这样的基本内容中:

var http = require('http');
http.createServer(function (req, response) {
// all requests return the results of calling _getMsg
// this function won't return until the callback completes
_getMsg('viT8B4KsRI7cJF2P2TS7Pd0mfqaI5rtwf', function (nodeArr) {
response.write(JSON.stringify(nodeArr));
response.end();
});
}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');

关于node.js - 获取 mongodb 数据到 nodejs 数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18822482/

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