reactjs - MERN Stack 应用程序相同的数据出现在其他用户仪表板中
问题描述
我尝试过两次寻求帮助,但没有得到适当的帮助来解决我遇到的问题。我正在尝试最后一次。我开始学习 MERN 堆栈并完成了一个小项目。但是,我遇到的问题是,当用户添加项目时,这些相同的项目会出现在另一个用户的仪表板上。我如何对其进行编码,以便登录用户只能看到他/她的数据?我正在学习很多关于这个堆栈的知识,所以如果我能就这个问题获得帮助,我将不胜感激。谢谢你。
****模型文件 Item.js 文件****
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
//Create Scheme
const ItemSchema = new Schema({
name:{
type: String,
required: true
},
date:{
type:Date,
default: Date.now
},
userId:{
type:Schema.Types.ObjectId,
ref: 'user'
}
});
module.exports = Item = mongoose.model('item', ItemSchema);
****api folder item.js code****
const express = require('express');
const router = express.Router();
const auth = require('../../middleware/auth');
//Item model`enter code here`
const Item = require('../../models/Item');
// @route GET api/items
// @description Get All Items
// Access Public
router.get('/', (req, res) =>{
Item.find({userId: req.body.userId})
.sort({ date: -1 })
.then(items => res.json(items));
});
// @route POST api/items
// @description Create an item
// Access Private
router.post('/', auth, (req, res) =>{
const newItem = new Item({
name: req.body.name,
userId: req.body.name
});
newItem.save().then(item => res.json(item));
});
// @route DELETE api/items/:id
// @description Delete an item
// Access Private
router.delete('/:id', auth, (req, res) =>{
Item.findById(req.params.id)
.then(item => item.remove().then(() => res.json({success:true})))
.catch(err => res.status(404).json({success: false}));
});
module.exports = router;
解决方案
我刚刚查看了您的架构,您在项目架构中没有用户标识符来匹配哪个用户添加了该项目,您如何找出哪个用户添加了哪个项目?
查看获取项目的路线,您正在查询获取所有项目,而不考虑用户 ID。
查询应该以某种方式构建
伪代码示例:
Item.find({where userId is currentUser.id})
.sort({ date: -1 })
.then(items => res.json(items));
推荐阅读
- java - 来自 ArrayList 的 ArrayList 的唯一集合
- java - 我怎么做才能让这个框架中的圆圈实际上自动移动?
- c# - 在这种情况下是否有另一种添加 Console.WriteLine() 的方法
- php - 在窗口 10 中安装 laravel 安装程序时出错
- vue.js - 创建组件并附加到父级的 Vue 指令
- powershell - 如何在 PowerShell 脚本中传递 Windows 凭据?
- python - 标记标签似乎在 TreeViewColumn 字符串的开头不起作用
- android - 构建项目时Android Studio中的AAPT错误
- javascript - 根据更改的属性数量创建对象数组
- android - 为什么是 todo-mvp-dagger,而不是 todo-mvvm-dagger?