【发布时间】:2020-08-25 04:31:43
【问题描述】:
我正在使用 mongoose 和 express 访问 MongoDB 中的数据,当我引用数据库时可以看到 JSON,但是当我尝试定位嵌套在其中的对象时,我收到一条未定义的消息。
用于访问数据库的 JS 文件。
const express = require('express');
const router = express.Router();
const skate_tricks = require('../models/SkateTrick');
router.get('/', (req, res) => {
skate_tricks.find({}, (err, result) => {
if (err) {
res.send(err);
} else {
res.send(result);
}
});
});
module.exports = router;
使用 Postman 的结果 sn-p
[
{
"trick_type": [],
"_id": "5f34a5782e0d2fe1c2847633",
"tricks": [
{
"trick_id": 0,
"trick_name": "ollie",
"trick_type": [
"flat"
],
"trick_difficulty": "n",
"trick_description": "Fundamental trick involving jumping with the skateboard. Performed by popping the tail with the back foot and sliding the front foot up towards the nose of the board. The sliding action levels the board while you are airborn."
}
]
}
]
我想直接访问对象的“tricks”数组,但它不起作用。
res.send(result.tricks);
【问题讨论】:
-
看来
result是一个数组,需要使用result[0].tricks来获取值。 -
您的结果变量是一个数组,因此您需要像这样访问它
result[0].tricks -
@HaoWu 当我尝试用你的方法控制台注销它时,我仍然不确定。我也注意到了,但不确定为什么它不起作用。
-
也许你可以试试
console.log(JSON.parse(JSON.stringify(result)))看看里面到底有什么 -
@HaoWu 我在控制台中得到了相同的结果。它表明数据被包裹在一个带有方括号的数组中。我以前使用过 JSON,但从未遇到过这个问题。
标签: javascript node.js json mongodb express