Node.js&JSON:访问对象属性
Node.js & JSON : Accessing object properties
我正在使用ExpressJS、NodeJS和Bookshelf.js
我试图查看用户的朋友列表,但如果我想访问对象的属性,就会出现"Unhandled rejection TypeError: Cannot read property 'friends' of undefined"
错误,如下所示:friends[0].friends[0].email
router.get('/relative', function (req, res) {
user.where('id', 1).fetchAll({withRelated: ['friends']}).then(function (friends) {
//res.send(friends);
res.json(friends); // works
res.send(friends[0].friends[0].email); // throws error
});
});
如果我在客户端尝试相同的JSON对象(只是手动复制返回的JSON并粘贴到fiddle),它会按预期工作。jsfiddle在下面。
http://jsfiddle.net/tmrd/zjzs4etu
我做错了什么?
res.send(friends)在上面给出了一个JSON对象,console.log(friends)返回的是:
CollectionBase {
model:
{ [Function]
NotFoundError: [Function: ErrorCtor],
NoRowsUpdatedError: [Function: ErrorCtor],
NoRowsDeletedError: [Function: ErrorCtor] },
length: 1,
models:
[ ModelBase {
attributes: [Object],
_previousAttributes: [Object],
changed: {},
relations: [Object],
cid: 'c2',
id: 1 } ],
_byId:
{ '1':
ModelBase {
attributes: [Object],
_previousAttributes: [Object],
changed: {},
relations: [Object],
cid: 'c2',
id: 1 },
c2:
ModelBase {
attributes: [Object],
_previousAttributes: [Object],
changed: {},
relations: [Object],
cid: 'c2',
id: 1 } },
_knex: null,
_events: {},
_eventsCount: 0 }
编辑2
[ { id: 1,
email: 'user1@gmail.com',
username: 'user1',
password_hash: '',
image_id: null,
name: '',
is_public: 0,
language_id: null,
notification_quote: 1,
phone: '',
notify_sms_password_change: 0,
notify_sms_diff_country_login: 0,
notify_sms_unusual_activity: 0,
search_engine_visibility: 0,
allowed_senders: 1,
use_ssl: 0,
notify_mail_friendship_request: 1,
notify_mail_comment_on_my_status: 1,
notify_mail_comment_on_my_photo: 1,
notify_mail_birthdays: 1,
notify_mail_app_game_request: 1,
invite_number_of_people: '0',
sms_login: 0,
notify_sms_different_ip: 0,
allowed_friendship_requests: 1,
email_key: '',
points: 0,
confirmation_code: '',
confirmed: 0,
status: 1,
deleted_at: '0000-00-00 00:00:00',
cover_image_id: null,
updated_at: '0000-00-00 00:00:00',
created_at: '0000-00-00 00:00:00',
type: 0,
friends: [ [Object], [Object] ] } ]
编辑:我将从查询中排除敏感列,这样它们在生产中就不可见了,这只是举个例子。
friends集合需要是json字符串才能发送。
router.get('/relative', function (req, res) {
user.where('id', 1).fetchAll({withRelated: ['friends']}).then(function (friends) {
//res.send(friends);
friends = friends.toJSON();
res.json(friends); // res.json automatically calls the toJSON method if the function is no json
res.send(friends[0].friends[0].email);
});
});
相关文章:
- 如何访问对象内部的“categoryIds”字段/键,该对象包含mongodb's `ObjectId(s)`数
- 使用js或extjs访问对象的java列表
- Javascript-访问对象
- 访问对象的最简单方法'的单独财产
- 分析云代码访问对象
- 如何从字符串变量访问对象属性
- 访问对象中的数组
- 如何访问对象's成员通过另一种方法填充的方法
- 访问对象内的数组
- 是否可以在定义对象时访问对象值
- Javascript 无法访问对象的属性
- $.each 中的“this”,当需要使用“this”访问对象的函数时
- 函数中的 angularJS 访问对象属性不起作用
- 通过存储在变量中的名称访问对象
- 访问对象内部的数组
- 如何从类函数内部访问对象属性
- 访问对象和指定变量
- Javascript - 使用 for 时遇到问题.以循环访问对象
- 为什么可以在内部函数成员中访问对象引用,而不能在内部属性成员中访问
- 当对象的键中有冒号时,如何访问对象属性