node.js - 尝试从数据库集合(mongodb)获取消息历史记录

标签 node.js mongodb chat history

我回到了带有历史记录的聊天系统,使用 mongodb,我不能说来自数据库集合的最后 20 条消息,我很确定这是关于添加到 find() 例程中的一些过滤,但我不知道在哪里以及如何做到这一点,这是我的代码:

MongoClient.connect('mongodb://127.0.0.1:27017/gt-chat', function(err, db) {
if(err) throw err;

var collection = db.collection('gt-chat');

console.log("******************************Printing docs from Cursor Each")

collection.find().each(function(err, doc) {
 console.log(doc);
if(doc != null) {
console.log("Doc from Each ");
console.dir(doc);
 }
});
});

此代码显示:

<小时/>

{ _id: 5488473660eda4ac251d6688, message: '敏捷的棕色狐狸跳过了懒狗' } 我不需要 _id 值,我只想要最后 20 条消息作为结果。 希望能够说得足够清楚, 预先感谢您对此的帮助! :)

最佳答案

你可以试试这个:

MongoClient.connect('mongodb://127.0.0.1:27017/gt-chat', function(err, db) {
   if(err) throw err;
   var collection = db.collection('gt-chat');
   console.log("******************************Printing docs from Cursor Each")
   collection.find({}, {_id: 0}).sort({$natural: 1}).limit(20).each(function(err, doc) {
      console.log(doc);
      if(doc != null) {
         console.log("Doc from Each ");
         console.dir(doc);
      }
   });
});

编辑

要写入浏览器,请使用 response 对象,如下所示

require('http').createServer(function(req, res) {
    MongoClient.connect('mongodb://127.0.0.1:27017/gt-chat', function(err, db) {
       if(err) throw err;
       var collection = db.collection('gt-chat');
       console.log("******************************Printing docs from Cursor Each")
       collection.find({}, {_id: 0}).sort({$natural: 1}).limit(20).each(function(err, doc) {
          console.log(doc);
          if(doc) {
             res.writeHead(200, {"Content-Type": "text/plain"});
             res.write(JSON.stringify(doc) + "\n");
          }
          else {
             res.end();
          }
      });
    });
}).listen(port, host);

关于node.js - 尝试从数据库集合(mongodb)获取消息历史记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27402282/

相关文章:

node.js - 在 XML 解析 block 期间从 socket.io 发出,直到处理完成

node.js https没有响应 'end'事件, 'close'代替?

node.js - 如何让 puppeteer 操纵者不被发现?

python - 如何在pandas中存储mongoDB嵌套文档而不重复

python - 在引用字段列表上使用 only() 进行 Mongoengine 查询

node.js - Stream.io 聊天从 Node.js 8.0 升级到 12.10

javascript - 滚动到 div 的底部?

node.js - AngularJS 和 ExpressJS session 管理?

sql - 数据库推荐

javascript - meteor .js : Doing message dependency like most of chat nowadays