繁体   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