Home > Mobile >  Mongooose: How to get a id from a find array
Mongooose: How to get a id from a find array

Time:09-19

I have a group-based document application, an error is happening in the sharing part. The application is composed of the following parts: Groups, viewers, users and documents.

A group can have many viewers and users, a user can have many documents. I'm working on the part where viewers can see all documents of users associated with the group the viewer is associated with

My controller

router.get("link", async (req, res) => {
        const group = await Group.find({ viewer: req.session.userId }).select("id")
        console.log(group); // This console.log returns the id in a array: [ { _id: new ObjectId("6323a88670c0dd9aaa5017d2") } ]
        console.log(group.id); // This console.log returns undefined

        const user = await User.find({ group: group.id });
        console.log(user); // Nothing because the group.id is undefined

        const documents = await Document.find({
          user: user.id,
        });

        return res.render("page", {
          documents,
        });

Group schema

  name: {
    type: String,
    required: true,
  },
  user: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "User",
    required: true,
  },
  viewer: [{
    type: mongoose.Schema.Types.ObjectId,
    ref: "User",
  }],
  createdAt: {
    type: Date,
    default: Date.now,
  }

I'm not able to retrieve the id from Group.find; what could be happening?

CodePudding user response:

Because you want to have one value. So you can use findOne. Due to using findOne, you can reach group._id.

const group = await Group.findOne({ viewer: req.session.userId }).select("id")
console.log(group); { _id: new ObjectId("6323a88670c0dd9aaa5017d2") }

If you try to take the value from your array, you should take 0. element of array. Because it is an array and has elements. You are trying to reach element's id value.

But which element's id ? You need to declare it. Therefore, need to use group[0]._id. But if you want to reach just one element, using findOne() is better.

const group = await Group.find({ viewer: req.session.userId }).select("id")
console.log(group[0]); { _id: new ObjectId("6323a88670c0dd9aaa5017d2") }

I hope, it is clear and helps you. Good luck

  • Related