0

These are the blog objects in the Database:

[
  {
    _id: 5fec92292bbb2c32acc0093c,
    title: 'Boxing ring',
    author: 'T. Wally',
    content: 'boxing stuff',
    likes: 0,
    user: {
      _id: 5fd90181d1e88a13109433f9,
      username: 'Johnny_23',
      name: 'John Q'
    },
    __v: 0
  },
  {
    _id: 5fec9481ce9c4a47a0ca6a2a,
    title: 'Football OP',
    author: 'RQ',
    content: 'it`s football',
    likes: 2,
    user: {
      _id: 5fec942dce9c4a47a0ca6a29,
      username: 'malcomm',
      name: 'Malcom'
    },
    __v: 0
  }
]

And i want to only find and show the blogs that belong to a certain user

listRouter.get('/', async (request, response) => {
  const blogs = await Blog
    .find({}).populate('user', { username: 1, name: 1 })

    response.json(blogs)
})

how can i access to the user id of every object and use it in a way that i can match the blogs?

  • 1
    Duplicate: [How to filter object array based on attributes?](https://stackoverflow.com/questions/2722159/how-to-filter-object-array-based-on-attributes) –  Dec 30 '20 at 14:36

2 Answers2

0

Since property user has _id, you can construct your query like this: const blogs = await Blog.find({ user: { _id: '_id of a certain user' } })

There will be a case where field user is a reference (its value is an ObjectId). In this case, try const blogs = await Blog.find({ user: '_id of a certain user' }).populate('user', { username: 1, name: 1 })

0

When you are posting a blog you are taking the user id as filed in data. You can also send the blog id to user collection so that it will be easy to populate data from user collection.

//push blogid to user blogsId filed
await UserModel.updateOne({ _id: req.body.userId }, {
    $push: {
      blogsId: blog._id
    }
})

You have to take a field in schema blogsId or whatever you want as an array field.