Home > Blockchain >  Mongoose: How to get back all docs that its flag value is true
Mongoose: How to get back all docs that its flag value is true

Time:01-31

I am using mongodb to store all my "post" within my website. I would like to find all documents that are "public"

My idea is to make a flag inside each document to indicate whether the post is public or private ... But I am not sure if this is a good approach for this in mongo

This is the scheme of my Doc. It represents a "Post". In its "public" field, this reflects whether it is public or not

This is the example: enter image description here

I would like to filter it in server-side. So, I handle this by mongoose.

But I am not sure if this approach or schema design for public/private is efficient or not.

Here is my idea to do it:

const ObjectId = require("mongodb").ObjectId;
 Post.aggregate([
      {
        $match: { _id: ObjectId(userId) }
      },
      {
        $match: { public: true }
      }

    ])
      .then((posts) => res.send(posts))
      .catch((error) => {
        console.log(error);
        res.sendStatus(400);
      });

It seems so strange and inefficient, so I would like to ask for a comment or improvement for the code above

CodePudding user response:

Its ok to have public flag to indicate whether post is public or private. You can try the following code to return all public documents.

Post.find({ public: true })
.then((posts) => res.send(posts))
.catch((error) => {
    console.log(error);
    res.sendStatus(400);
});

CodePudding user response:

Post.find({public: true}).then(result => {console.log(result)})
  •  Tags:  
  • Related