Stringify不会对虚拟填充对象进行字符串化

时间:2017-07-09 19:07:36

标签: javascript json node.js express ejs

这是我传递给视图的对象:

app.get('/view_add_requests', isLoggedIn, function (req, res) {
     var my_id = req.user._id;  // this is the senders id & id of logged in user


     FriendReq.find({to_id: my_id}).populate('profile').exec( function (err, result) {
             if(err) res.send(err);

             res.render('view_add_requests', { result : result });
     });
})

开启<%result%>在视图中打印

{ _id: 59625cbb2e9f1b7cdc968666, from_id: '59625cb52e9f1b7cdc968664', to_id: '59625caf2e9f1b7cdc968662', msg: 'Hi ! I would like to be your friend!', __v: 0, profile2: null, profile: [ { _id: 59625cb52e9f1b7cdc968665, about: 'null', status: 'Happy', picture: 'https://scontent.xx.fbcdn.net/v/t1.0-1/p200x200/17361955_10208706527529679_1126407854127685629_n.jpg?oh=a4fc39a10fed1abf09bf526046aaa671&oe=5A038BFC', work: 'Duopod Design Limited', language: 'Hindi', relationship_status: 'Single', interested_in: 'female', location: 'Auckland, New Zealand', birthday: '03/28/1993', gender: 'male', name: 'Andy Karwal', id: '10209588148249646', __v: 0, user_id: [Object] } ], id: '59625cbb2e9f1b7cdc968666' }

在我的console.log(结果)路线中打印:

[ { _id: 59625cbb2e9f1b7cdc968666,
from_id: '59625cb52e9f1b7cdc968664',
to_id: '59625caf2e9f1b7cdc968662',
msg: 'Hi ! I would like to be your friend!',
__v: 0,
profile2: null,
profile: [ [Object] ],
id: '59625cbb2e9f1b7cdc968666' } ]

<%= JSON.stringify(result) %> 

打印

[{"_id":"59625cbb2e9f1b7cdc968666","from_id":"59625cb52e9f1b7cdc968664","to_id":"59625caf2e9f1b7cdc968662","msg":"Hi ! I would like to be your friend!","__v":0}]

Stringify似乎忽略了嵌套的Object。我如何在视图中访问它? JSON.parse(result)返回**error: unexpected token _ in JSON at position 2** 香港专业教育学院尝试过:

<%- result._id %> <%- result.profile[0].name %> <%- result["_id"] %>

所有返回未定义。如何访问“配置文件”中的虚拟填充字段,即名称,图片等?请指导。

1 个答案:

答案 0 :(得分:0)

我用return this.http.get(this.apiUrl + 'people/') .map(response => { return response.json(), console.log(response.json()); })

修复此问题
相关问题