Node.js Mongoose,一种简洁的方法,可以将一个具有每个唯一属性的项放入一个数组中?

Node.js Mongoose,一种简洁的方法,可以将一个具有每个唯一属性的项放入一个数组中?,node.js,mongodb,mongoose,Node.js,Mongodb,Mongoose,我收集了许多不同特点的文件。我想从Mongoose获取一个数组,其中数组中的每个项都是属性的唯一值,在本例中为color。换句话说,我不需要每个项目的数组,只需要颜色值的数组。所以在本例中,若我有100种不同的产品,但在所有100种颜色之间只有8种颜色,那个么我希望有一个8种颜色的数组。这是我一直在使用的方法,但我想知道是否有更简洁的方法 var allproducts = Products.find(function (err, products) { // Get all pro

我收集了许多不同特点的文件。我想从Mongoose获取一个数组,其中数组中的每个项都是属性的唯一值,在本例中为
color
。换句话说,我不需要每个项目的数组,只需要颜色值的数组。所以在本例中,若我有100种不同的产品,但在所有100种颜色之间只有8种颜色,那个么我希望有一个8种颜色的数组。这是我一直在使用的方法,但我想知道是否有更简洁的方法

  var allproducts = Products.find(function (err, products) {
    // Get all products
    var collection = [];
    // Make an array to contain a product with each of the 8 colors
    var uniqueArray = [];
    // Make an array to check the current color against (if already used)
    for (var i = products.length - 1; i >= 0; i--) {
      if (uniqueArray.indexOf(products[i].color) === -1) {
        // Check to see if the color is in the unique color array
        uniqueArray.push(products[i].color);
        // Add it if not
        collection.push(products[i]);
        // Add the product to the collection array if its color is not in the unique array
      }
    }
  });
试图使用Mongoose
聚合方法

router.get('/', function (req, res) {
  Products.aggregate([{
    $group: {
      _id: '$color'
    }
  }], {}, function (err, collection) {
    console.log(err, collection);
    if (err) {
      throw err
    }
    res.end();
    // res.json(collection);
  });
});

I.直接在mongodb中,您必须满足以下要求:

 db.colors.aggregate( { $group: {_id:"$color"} } )
结果:

{ "_id" : "yellow" }
{ "_id" : "blue" }
{ "_id" : "red" }

二,。在猫鼬中,您可以执行以下操作:

Products.aggregate(
     {$group: {
            _id: '$color' // grouping key - group by field district
     }
 }).exec( function( err, products ) {
    if ( err ) {
      return res.status( 400 ).send({
        message: errorHandler.getErrorMessage( err )
      });
    } else {
      res.json( products );
    }
 });

使用


您可能正在寻找
distinct
这是获取单个唯一颜色的好方法,但是我希望获得第一个具有每个唯一颜色的完整文档。第一个文档直接在Mongo中工作,但在Mongoose中我得到:
[错误:参数必须是聚合管道运算符]
请尝试:Products.aggregate({$group:{{u id:'$color'//grouping key-group by field district},{},callback)//没有[],因为我们没有聚合函数的列表很抱歉,请尝试:Products.aggregate({$group:{{u id:'$color'}}).exec(函数(err,data){if(err){/}else{/});更新:Products.aggregate({$group:{{u id:'$color'//分组键-按字段区域分组}}).exec(函数(err,产品){if(err){return res.status(400).send({message:errorHandler.getErrorMessage(err)})}else{res json(产品)});旁注,倒勾,这些(```)使内联代码示例更易于阅读
npm install lodash --save

var _ = require('lodash');

var allproducts = Products.find(function (err, products) {
    ...
    var uniqueArray = _.pluck(products, 'color');
    uniqueArray = _.uniq(uniqueArray);
    ....  
});