我回到了带有历史记录的聊天系统,使用 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/