[英]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)
很久以前就和我有过这个问题。 希望这对你也有帮助!
Model.findOne()
/ Mondel.findById()
/ Model.find()
获取 MongoDB 中的数据data
中。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! 这里是!
您可以通过以下方式从数据库中获取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.