遍历和过滤Express和Mongoose中的数据 [英] Looping through and filtering the data in express and mongoose
问题描述
我有一个使用Node.js,Express和Mongoose的后端.我试图过滤嵌套在对象深处的文档数组,但是由于某种原因我无法访问该数组.路由 req
包含已登录用户的附加文档.以下是mycode.
I have a backend with Node.js, Express and Mongoose. I am trying to filter an array of documents that is nested deep in an object but I am not able to access the array for some reason. The route req
has an attached document of the user who is logged in. Below is mycode.
router.post("/users/:id/accept", auth, async (req, res) => {
try {
// this filter is not working
await req.user.friendRequests.filter((usr) => usr.owner !== req.params.id);
await req.user.save();
res.send("Accepted")
} catch (error) {
res.status(400).send(error.message);
}
});
如果我 console.log(req.user)
,我得到:
{
dateOfBirth: { date: 28, month: 'Sep', year: 2002 },
gender: 'male',
cover: null,
_id: 5f71c0674a54b03e70fcbe97,
firstName: 'jake',
lastName: 'sulli',
email: 'hello2@gmail.com',
friendRequests: [
_id: 5f71c1184a54b03e70fcbea0,
owner: '5f71c0d14a54b03e70fcbe9b',
friend: false,
name: 'mad max'
},
{
_id: 5f76a7872b21c8208f3caa5f,
owner: '5f742182931ab9125bc2ec9d',
friend: false,
name: 'shriya rai'
},
{
_id: 5f76f6fa85e74758e76cb1ec,
owner: '5f76f541ab7a1255dc78987d',
friend: false,
name: 'dara singh'
}
],
}
如果我 console.log()
,我将无法获取 friendRequests
数组,但是我可以获取 name
, email
和 gender
.我要实现的是,如果 friendRequests.owner === req.params.id
,那么我想从数组中删除该对象.
I am not able to get the friendRequests
array if I console.log()
but I can get name
, email
, and gender
. What I want to achieve is, if the friendRequests.owner === req.params.id
then I want to remove that object from the array.
推荐答案
您的 friendRequests
数组存在一些问题.
There are a few issue with your friendRequests
array.
首先,您没有正确开始或结束对象.
First you didn't begin or end your object correctly.
friendRequests: [
{ <=========================== Need another bracket
_id: 5f71c1184a54b03e70fcbea0,
owner: '5f71c0d14a54b03e70fcbe9b',
friend: false,
name: 'mad max'
},
{
_id: 5f76a7872b21c8208f3caa5f,
owner: '5f742182931ab9125bc2ec9d',
friend: false,
name: 'shriya rai'
},
{
_id: 5f76f6fa85e74758e76cb1ec,
owner: '5f76f541ab7a1255dc78987d',
friend: false,
name: 'dara singh'
}
]
第二,确保将_id转换为字符串
Second make sure you make those _id into string
5f76f6fa85e74758e76cb1ec to "5f76f6fa85e74758e76cb1ec"
这篇关于遍历和过滤Express和Mongoose中的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!