简体   繁体   English

加入两个收藏夹并在猫鼬中对其进行排序

[英]Join two collections and sort them in Mongoose

I have two separate collections, suppose news and pictures . 我有两个单独的收藏,假设newspictures Both collections have a creationDate field that holds a datetime of records creation time. 这两个集合都有一个creationDate字段,该字段保存记录创建时间的datetime时间。

What I want is to select last 10 records from both collections, join all records (now the list has 20 records) and then sort all records by creationDate field. 我想要从两个集合中选择最后10条记录,加入所有记录(现在列表中有20条记录),然后按creationDate字段对所有记录进行排序。 How it's possible in Mongoose? 猫鼬怎么可能?

Well what you are asking for is essentially a client side operation, and you really only want at most 20 records to sort so that should not be a problem. 好吧,您所要求的实际上是一个客户端操作,并且您实际上只希望对20条记录进行排序,所以这应该不是问题。

The async.concat method should help a little here: async.concat方法应该在这里有所帮助:

async.concat([News,Picture],function(model,callback) {
  // Get the last 10 results from each collection
  var query = model.find({}).sort({ "creationDate": -1 }).limit(10);
  query.exec(function(err,docs) {
    if (err) throw err;
    callback(err,docs);
  });
},
function(err,result) {
  if (err) throw err;
  // results are merged, now sort by date
  result = result.sort(function(a,b) {
    return (a.creationDate < b.creationDate) 
      ? 1 : (a.creationDate > b.creationDate) ? -1 : 0;
  });
  console.log(result);

});

So really you are just "merging" two arrays, but coding it that way simplifies things. 因此,实际上您只是在“合并”两个数组,但是以这种方式进行编码可以简化事情。


An end to end listing to clarify the usage here. 端到端清单以在此处阐明用法。 This sets up some documents for each model before running the code as shown above: 这将在运行代码之前为每种模型设置一些文档,如下所示:

var async = require('async'),
    mongoose = require('mongoose'),
    Schema = mongoose.Schema;

mongoose.connect('mongodb://localhost/series');

var newsSchema = new Schema({
  type: { type: String, default: "News" },
  index: Number,
  creationDate: { type: Date, default: Date.now }
});

var pictureSchema = new Schema({
  type: { type: String, default: "Picture" },
  index: Number,
  creationDate: { type: Date, default: Date.now }
});

var News = mongoose.model( "News", newsSchema );

var Picture = mongoose.model( "Picture", pictureSchema );

async.series(
  [
    // Clean existing
    function(callback) {
      async.each([News,Picture],function(model,callback) {
        model.remove(function(err) {
          if (err) throw err;
          callback();
        });
      },function(err) {
        callback();
      });
    },

    // Insert 20 of each
    function(callback) {
      console.log("inserting");
      var count = 0;
      async.whilst(
        function() { return count < 20 },
        function(callback) {
          count++;
          async.eachSeries([News,Picture],function(model,callback) {
            var doc = new model({ index: count });
            setTimeout(function() {
              doc.save(function(err) {
                if (err) throw err;
                callback();
              });
            }, 20);
          },function(err) {
            callback();
          });
        },
        function(err) {
          callback();
        }
      );
    }
  ],
  function(err) {
    console.log("listing");

    // Get the last 10 of each
    async.concat([News,Picture],function(model,callback) {
      var query = model.find({}).sort({ "creationDate": -1 }).limit(10);
      query.exec(function(err,docs) {
        if (err) throw err;
        callback(err,docs);
      });
    },
    function(err,result) {
      if (err) throw err;

      // result is merged via "concat" now sort it.
      result = result.sort(function(a,b) {
        return (a.creationDate < b.creationDate)
          ? 1 : (a.creationDate > b.creationDate)
          ? -1 : 0;
      });
      console.log(result);
      mongoose.disconnect();
    });
  }
);

Output is somewhere along these lines: 输出在以下几行中:

[ { _id: 53c79f4b7daf2d676ff0f185,
    index: 20,
    __v: 0,
    creationDate: Thu Jul 17 2014 20:02:51 GMT+1000 (EST),
    type: 'Picture' },
  { _id: 53c79f4b7daf2d676ff0f184,
    index: 20,
    __v: 0,
    creationDate: Thu Jul 17 2014 20:02:51 GMT+1000 (EST),
    type: 'News' },
  { _id: 53c79f4b7daf2d676ff0f183,
    index: 19,
    __v: 0,
    creationDate: Thu Jul 17 2014 20:02:51 GMT+1000 (EST),
    type: 'Picture' },
  { _id: 53c79f4b7daf2d676ff0f182,
    index: 19,
    __v: 0,
    creationDate: Thu Jul 17 2014 20:02:51 GMT+1000 (EST),
    type: 'News' },
  { _id: 53c79f4b7daf2d676ff0f181,
    index: 18,
    __v: 0,
    creationDate: Thu Jul 17 2014 20:02:51 GMT+1000 (EST),
    type: 'Picture' },
  { _id: 53c79f4b7daf2d676ff0f180,
    index: 18,
    __v: 0,
    creationDate: Thu Jul 17 2014 20:02:51 GMT+1000 (EST),
    type: 'News' },
  { _id: 53c79f4b7daf2d676ff0f17f,
    index: 17,
    __v: 0,
    creationDate: Thu Jul 17 2014 20:02:51 GMT+1000 (EST),
    type: 'Picture' },
  { _id: 53c79f4b7daf2d676ff0f17e,
    index: 17,
    __v: 0,
    creationDate: Thu Jul 17 2014 20:02:51 GMT+1000 (EST),
    type: 'News' },
  { _id: 53c79f4b7daf2d676ff0f17d,
    index: 16,
    __v: 0,
    creationDate: Thu Jul 17 2014 20:02:51 GMT+1000 (EST),
    type: 'Picture' },
  { _id: 53c79f4b7daf2d676ff0f17c,
    index: 16,
    __v: 0,
    creationDate: Thu Jul 17 2014 20:02:51 GMT+1000 (EST),
    type: 'News' } ]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM