简体   繁体   中英

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?

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.

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() .
  2. Now we have the data somewhere, lets say we stored it in a variable, data .
  3. Almost there, we now gotta get that module1 key passed. you should, by now, have data = something like this:
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! here it is!

  1. Sending the module1 to React. Since I'm not that familiar with react, please check this and this .

You may get module1 from the database either through this way:

API to send data to frontend:

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:

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:

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:

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>;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM