首页 > 解决方案 > 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;

标签: reactjsmongodbmongodb-querymongoose-schemamern

解决方案


我刚刚查看了您的架构,您在项目架构中没有用户标识符来匹配哪个用户添加了该项目,您如何找出哪个用户添加了哪个项目?

查看获取项目的路线,您正在查询获取所有项目,而不考虑用户 ID。

查询应该以某种方式构建

伪代码示例:

Item.find({where userId is currentUser.id})
    .sort({ date: -1 })
    .then(items => res.json(items));

推荐阅读