简体   繁体   English

如何从 mongodb 中获取单个项目并显示它? (默恩)

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

How can I only fetch module 1 from mongodb and display it onto react?如何仅从 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);

I've seen many ways of fetching an array of items from mongodb and displaying it using the.map function, but I just want to display a single item (module1) from the User Schema above to my react app.我已经看到了许多从 mongodb 获取项目数组并使用.map function 显示它的方法,但我只想从用户模式 1 上显示我的单个项目(用户模式 1)

Had this problem with me quite a while ago.很久以前就和我有过这个问题。 Hope this helps you too!希望这对你也有帮助!

  1. First of all, in your router.js or server.js backend server/route file, get the data in MongoDB with Model.findOne() / Mondel.findById() / Model.find() .首先,在您的 router.js 或 server.js 后端服务器/路由文件中,使用Model.findOne() / Mondel.findById() / Model.find()获取 MongoDB 中的数据
  2. Now we have the data somewhere, lets say we stored it in a variable, data .现在我们在某个地方有了数据,假设我们将它存储在一个变量data中。
  3. Almost there, we now gotta get that module1 key passed.快到了,我们现在必须让module1密钥通过。 you should, by now, have data = something like this:你现在应该有 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,
}]

pretty simple, get it out of the array and the Object, do var module 1 = data[0].module1 .Voila!很简单,把它从数组Object 中取出,做var module 1 = data[0].module1 .Voila! here it is!这里是!

  1. Sending the module1 to React.module1发送到 React。 Since I'm not that familiar with react, please check this and this .由于我对 react 不太熟悉,请检查thisthis

You may get module1 from the database either through this way:您可以通过以下方式从数据库中获取module1

API to send data to frontend: 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,
  });
});

Retrieving data from API:从 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>;
}

Or through this way:或者通过这种方式:

API to send data to frontend: 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,
  });
});

Retrieving data from API:从 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