我從資料庫獲取資料有問題。我想從 mongoDB 獲取“集合”陣列并將其呈現在表組件中,但由于問題“未找到用戶”,查詢回傳 null。有趣的是,如果我在 updateOne 查詢中使用 {email: req.body.email} 來搜索用戶,然后創建新的集合,它就可以作業并找到用戶。getCollections.js
const router = require("express").Router();
const User = require("../models/user");
router.get("/", (req, res) => {
var query = { email: req.body.email };
User.find(query, (err, result) => {
if (err) {
res.json({ status: "error", error: "User not found" }, err);
} else {
res.json(result);
}
});
});
module.exports = router;
前端 getCollections 查詢
useEffect(() => {
const url = "http://localhost:5000/api/getCollections";
// const url = `https://item-collection-app-bz.herokuapp.com/api/getCollections`;
axios
.get(url, { email: localStorage.getItem("email") })
.then((response) => {
setListOfCollections(response.data);
});
});
user.js 用戶架構
const jwt = require("jsonwebtoken");
const mongoose = require("mongoose");
const userSchema = new mongoose.Schema({
_id: { type: mongoose.Schema.Types.ObjectId, required: true },
username: { type: String, require: true },
password: { type: String, require: true },
email: { type: String, require: true },
admin: { type: Boolean },
blocked: { type: Boolean },
collections: [
{
_id: { type: mongoose.Schema.Types.ObjectId, required: true },
coll_name: { type: String },
type: { type: String },
coll_desc: { type: String },
coll_image: { type: String },
items: [
{
_id: { type: mongoose.Schema.Types.ObjectId, required: true },
item_name: { type: String },
item_desc: { type: String },
comments: [
{
user: { type: String },
comment: { type: String },
comment_id: { type: String },
},
],
likes: { type: Number },
item_image: { type: String },
upload_date: { type: String },
},
],
},
],
});
userSchema.methods.generateAuthToken = function () {
const appToken = jwt.sign({ _id: this._id }, process.env.JWTPRIVATEKEY, {
expiresIn: "7d",
});
return appToken;
};
const User = mongoose.model("user", userSchema);
module.exports = User;
mongoDB mongoDB結構
試過 User.findOne(), User.find()
解決方案
謝謝@Varun Kaklia。解決方案是將 router.get 和 axios.get 更改為 router.post 和 axios.post。
uj5u.com熱心網友回復:
嘿@1zboro1 首先檢查您是否從路由內的前端收到任何資料,例如-
const router = require("express").Router();
const User = require("../models/user");
router.get("/", (req, res) => {
const email = req.body.email;
console.log("Email from frontend", email)
var query = { email: req.body.email };
if (email != null || undefined) {
try {
const user = await User.find({ email});
console.log("User Details in User Routes of Backend",user)
if (user.length > 0) {
const currentUser = {
name: user[0].name,
email1: user[0].email1,
isAdmin: user[0].isAdmin,
_id: user[0]._id,
};
// console.log("Get User in User Routes of Backend", currentUser)
res.status(200).send(currentUser);
}
} catch (error) {
res.status(404).json({
message: "Something Went wrong",
});
}
希望此代碼能解決您的查詢并為您提供所需的結果。如果您仍然面臨問題,請讓我知道。謝謝
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/525215.html
上一篇:使用javascript創建的元素未出現在req.body中
下一篇:Mongo聚合$skip失敗
