【问题标题】:Mongoose and Express, How can I get unique records from db?Mongoose 和 Express,如何从 db 中获取唯一记录?
【发布时间】:2018-07-06 17:20:48
【问题描述】:

在我的数据库中,我有 2-3 条记录为 title(第一条)。 我怎样才能只得到 1 个结果?

以下是我的代码不起作用,

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
    });
   }
  });
});

但如果我使用,

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

它有效,但我不需要对象,因为它们都是唯一的

我试过这个链接 How do I query for distinct values in Mongoose?

但这对我不起作用。

例如,我有记录:

一,二,一

但需要输出:一,二

【问题讨论】:

  • 真的很难理解你在这里寻找什么,你能添加一个示例输入和你的预期输出吗?
  • 我已经举了一个例子
  • 还是像泥一样清澈。您是否期待一组文档,例如 [{ _id: 'xxxx', title: 'One' }, { _id: 'yyy', title: 'Two' }] 或只是一个字符串数组,即标题 ['One', 'Two']

标签: node.js mongodb mongoose


【解决方案1】:

您需要使用distinct 运算符,并像这样作为参数传递所需的属性(此处为标题),

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
      });
    }
  });
});

以下查询将返回一个 title 数组,全部不同。

希望这能解决问题。

【讨论】:

    猜你喜欢
    • 2021-03-21
    • 1970-01-01
    • 2013-04-21
    • 1970-01-01
    • 2019-03-20
    • 2016-09-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-16
    相关资源
    最近更新 更多