簡體   English   中英

無法使用點表示法定位 JSON 中的嵌套對象

[英]Unable to target a nested object in JSON by using dot notation

我正在使用 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 的結果片段

[
    {
        "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."
            }
        ]
    }
]

我想直接訪問對象的“技巧”數組,但它不起作用。

res.send(result.tricks);

你的結果對象是一個對象數組。

[
    {
        "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."
            }
        ]
    }
]

所以你必須使用res.send(result[0].tricks);來訪問它res.send(result[0].tricks); 或更改您的 API 響應以返回它

嘗試為您的貓鼬模型添加tricks

const mongoose = require("mongoose");
const SkateTrickSchema = new mongoose.Schema({
  trick_id: { type: Number, required: true, unique: true },
  trick_name: { type: String, unique: true },
  trick_type: { type: Array, required: true },
  trick_difficulty: { type: String, required: false },
  trick_description: { type: String, required: false },
  tricks: { type: Array, required: true }
});
module.exports = SkateTrick = mongoose.model(
  "skateboard-tricks",
  SkateTrickSchema
);

您可以嘗試的一件事是將.lean()添加到您的查詢中

router.get("/", async (req, res) => {
  try {
    let result = await skate_tricks.find({}).lean();
    res.send(result);
  } catch (err) {
    res.send(err);
  }
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM