【问题标题】:How to get Json Data from MongoDB against a specific User who posted it?如何针对发布它的特定用户从 MongoDB 获取 Json 数据?
【发布时间】:2021-12-08 00:39:37
【问题描述】:
router.post('/',auth, async (req, res) => {

const { error } = validate(req.body); //Error Check
  if (error) return res.status(400).send(error.details[0].message);

  let property = new Property({  //Creating Object: Property as per defined Schema:
    title: req.body.title,
    description: req.body.description,
    price: req.body.price,

    user: {
      _id: req.user._id, //Getting the ID from auth middleware with JWT Token Authenticared
    }
  });
  console.log({property});
  await property.save(); //Saving the Object
  
  res.send(property); //Displaying User with created Object i.e. Property
});

我正在使用 POST 方法创建一个属性。

现在我想从 MongoDB 获取数据,但仅限于当前登录并创建该数据的用户。


  //Writing a GET METHOD to List of Properties with Valid Token:
router.get('/', async (req,res)=>{
  try{
  
  //Getting the Information of User by the current user.id loggin in: ... .select('-password') sets it to don't show password
  const property = await Property.findById(req.user );
  res.send(property);
  }
  
  catch (ex){
      console.error(ex.message);
  }
  });

【问题讨论】:

  • 您能否请edit 您的问题显示实际的属性模型架构定义?我认为user 字段是User 模型的引用,即{ type: Schema.Types.ObjectId, ref: 'User' }

标签: node.js mongodb mongoose


【解决方案1】:

而不是findByIdtry find({user: req.user._id})

req.user 包含经过身份验证的用户信息,因此通过使用_id,我们可以获得帮助我们过滤特定用户创建的属性的 ID

【讨论】:

    猜你喜欢
    • 2020-08-13
    • 2019-11-08
    • 2022-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多