把手,JS和节点

问题描述 投票:0回答:1

我正试图抓住服务器从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已经不知何故已经是一个对象。

javascript node.js mongodb handlebars.js
1个回答
1
投票

对服务器上的对象进行字符串化,然后在客户端上访问它。

//server
res.render('partials/map', {docs: JSON.stringify(doc)})

//client
var docs = {docs}
© www.soinside.com 2019 - 2024. All rights reserved.