gpt4 book ai didi

javascript - Node : javascript array issue

转载 作者:行者123 更新时间:2023-11-30 16:05:52 25 4
gpt4 key购买 nike

我有这个 node.js 应用程序,它使用 mongoose 从 mongodb 检索地铁数据,在我获得数据后,我将把它传递给 sphere-knn计算最近的点。奇怪的事情发生在 var lookup = sphereKnn(d1); 如果我传递 d1 这是硬编码数组,代码将工作,如果我传递 data 从 mongodb 中检索,它根本不起作用,并返回空数组作为结果。

JSON.stringify(data) == JSON.stringify(d1) 将打印 trueArray.isArray 也将打印 true 对于 d1dataconsole.log 将显示变量 data 中有数据>.

我对代码的行为感到困惑。我来自 .net 和 node.js 的新手。我在这里错过了什么重要的概念吗?

mrtStop.find({}, {_id:0}, function(err, data){
if(err){
return res.json(err);
}

// data returned from mongodb, get first one
data = data.slice(0,1);

// hard coded data
var d1 = [{"id":"EW6",
"name":"EXAMPLE MRT STATION",
"lat":1.3210355412,
"lon":103.9129310102,
"__v":0}];

console.log(JSON.stringify(data));
console.log(JSON.stringify(d1));
// print true
console.log(JSON.stringify(data) == JSON.stringify(d1));

// d1 works, but data won't work
// var lookup = sphereKnn(d1);
var lookup = sphereKnn(data);

var points = lookup(req.query.lat, req.query.lon, maxNum);

res.json(points);
});

最佳答案

使用Query.lean()

tldr; mongoose 返回 mongoose-doc 对象,它有很多原型(prototype),当你学习它时,它会返回 plain js对象

//side note: you could also remove `__v` property {_id: 0, __v:0}
mrtStop.find({}, {_id:0}).lean().exec(function(err, data){
if(err){
return res.json(err);
}
var lookup = sphereKnn(data);
var points = lookup(req.query.lat, req.query.lon, maxNum);
res.json(points);
});

关于javascript - Node : javascript array issue,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37064988/

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