我正在尝试获取服务器从 MongoDB 发送的数据。常规 GET:
.get('/test', function(req, res){
mongo.collection('collection').find({ _id:req.user._id.toString()
}).toArray( function(err, doc){
res.render('partials/map',
{ docs : doc });
}
});
});
即将包含文档的数组发送给客户端。然后我想在客户端操作数据,所以我在客户端的 javascript 中执行以下操作:
<script>
var docs = '{{docs}}';
console.log(typeof(docs));
console.log(docs);
var obj = new Object(docs);
console.log(obj);
var arr = new Array(docs);
console.log(arr);
console.log(JSON.stringify(docs));
</script>
但是,我不知道如何实际操作它,因为上面只给了我以下输出(在控制台中):
string
[object Object],[object Object],[object Object]
String {"[object Object],[object Object],[object Object]"}
["[object Object],[object Object],[object Object]"]
"[object Object],[object Object],[object Object]"
如何操作数据?我知道它是一个包含三个文档的数组,但只需尝试 docs[0] 就会给出 [object Object] 中的第一个字符(即“[”)。另外, JSON.parse(docs) 只是返回错误,因为 docs 不知何故已经是一个对象。
最佳答案
在服务器上对对象进行字符串化,然后在客户端上访问它。
//server
res.render('partials/map', {docs: JSON.stringify(doc)})
//client
var docs = {docs}
关于javascript - Handlebars 、JS 和 Node,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49107587/