Pavel Coder
Pavel Coder

Reputation: 33

Mongoose and Express, How can I get unique records from db?

In my database, I have 2-3 records with title (Article one). How can I get only 1 result?

Following is my code that doesn't work,

app.get('/', (req, res) => {
  Article.find.distinct(title, (err, title) => {    
  if(err){
  console.log(err);
} else {
  console.log(articles);
  res.render('index', {
    title: 'Articles',
    articles: title
    });
   }
  });
});

But if I use,

Article.find({}, (err, title)

it works, but I do not need objects because they are all unique

I tried this link How do I query for distinct values in Mongoose?

But it does not work for me.

For example, I have records:

One, Two, One

But need output: One, Two

Upvotes: 2

Views: 2835

Answers (1)

Nilesh Singh
Nilesh Singh

Reputation: 1750

You need to use distinct operator with the desired property (here, title) passed as parameter like this,

app.get('/', (req, res) => {
  Article.distinct('title', function(error, titles) { //see the use of distinct
    if (err) {
       console.log(err);
    } else {
      console.log(articles);
      res.render('index', {
         title: 'Articles',
         articles: titles
      });
    }
  });
});

The following query will return an array of title, all distinct.

Hope this resolves the issue.

Upvotes: 1

Related Questions