簡體   English   中英

如何從 mongodb 中獲取單個項目並顯示它? (默恩)

[英]How do you fetch a single item from mongodb and display it? (MERN)

如何僅從 mongodb 獲取模塊 1 並將其顯示到反應中?

const userSchema = new mongoose.Schema({
  username: String,
  password: String,
  module1: Number,
  module2: Number,
  module3: Number,
  module4: Number,
  module5: Number,
  module6: Number,
  module7: Number,
  module8: Number,
  module9: Number,
  module10: Number,
});
const User = mongoose.model("User", userSchema);

我已經看到了許多從 mongodb 獲取項目數組並使用.map function 顯示它的方法,但我只想從用戶模式 1 上顯示我的單個項目(用戶模式 1)

很久以前就和我有過這個問題。 希望這對你也有幫助!

  1. 首先,在您的 router.js 或 server.js 后端服務器/路由文件中,使用Model.findOne() / Mondel.findById() / Model.find()獲取 MongoDB 中的數據
  2. 現在我們在某個地方有了數據,假設我們將它存儲在一個變量data中。
  3. 快到了,我們現在必須讓module1密鑰通過。 你現在應該有 data = 像這樣的東西:
var data = 
[{
     username: String,
  password: String,
  module1: Number,
  module2: Number,
  module3: Number,
  module4: Number,
  module5: Number,
  module6: Number,
  module7: Number,
  module8: Number,
  module9: Number,
  module10: Number,
}]

很簡單,把它從數組Object 中取出,做var module 1 = data[0].module1 .Voila! 這里是!

  1. module1發送到 React。 由於我對 react 不太熟悉,請檢查thisthis

您可以通過以下方式從數據庫中獲取module1

API 向前端發送數據:

const app = express(),
  User = require('./models/User');

app.get('/api/user/:id', async (req, res) => {
  const { id } = req.params;
  const user = await User.findById(id);

  res.json({
    success: true,
    user,
  });
});

從 API 檢索數據:

export default function StackOverflow() {
  import React, { useEffect } from 'react';
  import axios from 'axios';

  const getResponse = async () => {
    const res = await axios.get(`http://localhost:3000/api/user/${userId}`);

    console.log(res.data.user.module1);
  };

  useEffect(() => {
    getResponse();
  }, []);

  return <div></div>;
}

或者通過這種方式:

API 向前端發送數據:

const app = express(),
  User = require('./models/User');

app.get('/api/user/:id', async (req, res) => {
  const { id } = req.params;
  const { module1 } = await User.findById(id).select('-_id module1');

  res.json({
    success: true,
    module1,
  });
});

從 API 檢索數據:

export default function StackOverflow() {
  import React, { useEffect } from 'react';
  import axios from 'axios';

  const getResponse = async () => {
    const res = await axios.get(`http://localhost:3000/api/user/${userId}`);

    console.log(res.data.module1);
  };

  useEffect(() => {
    getResponse();
  }, []);

  return <div></div>;
}

暫無
暫無

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

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