arrays - 输出mongoose中的所有文档

标签 arrays node.js mongodb object mongoose

我正在使用 mongoose ODM,并且有一个如下所示的架构:

var banSchema = new Schema({
  userid: { type: String, required: true, unique: true },
  name: String,
  groupid: String,
  reason: String,
  timestamp: Date
});

我想输出集合中所有文档中的每个用户 ID。我正在使用此查询来获取 userid 对象。但是我似乎无法自动获取完整列表。我必须手动输入对象编号,如下所示:

bot.onText(/\/sync/i, function (msg) {
    var fromId = msg.from.id;
    var chatId = msg.chat.id;
    if (fromId == config.sudo) {
        console.log('Sudo Confirmed And Authorized!');
        Ban.find({}, function (err, obj) {
            console.log(obj[0].userid);  // Returns A Single ID
            console.log(obj[1].toObject().userid); // Returns a different ID
            bot.sendMessage(chatId, obj[1].toObject().useridid);
        });
    } else {
        console.log('Someone Is Trying To Act Like Sudo! *sigh*');
        bot.sendMessage(chatId, 'You Are Not A Mod!');
    }
});

然而,这并没有像我想要的那样返回完整的 id 列表。我该如何解决这个问题?

上面的代码适用于电报机器人,在 /sync 命令上,它应该返回一条包含集合中所有 ID 的消息。

Telegram 机器人 API 限制

由于 API 限制,整个输出应位于单个消息中。

最佳答案

var query = Ban.find({}).select({
            "userid": 1,
            //Add more column fields here
            "_id": 0  //Ensures _id is not displayed
            });
            var arr = [];
            query.exec(function (err, results) {
                   if (err) throw err;
                   results.forEach(function (result) {
                   arr.push(result.userid);
                   // Add more column fields here;
                   });
                   var fixedJoin =arr.join("\n"); 
                         console.log(fixed);
                   bot.sendMessage(chatId, 'List\n\n' + fixedJoin);
            });

关于arrays - 输出mongoose中的所有文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38880660/

相关文章:

java - Java 消除数组中的重复数字

c++ - 在 C++ 中使用 memcpy

javascript - 如何访问我的 Google Play 开发者帐户中的存储桶?

node.js - 尝试通过 mongoose 使用 Node js 将对象保存在文档上时出现问题

node.js - yarn 抛出错误 : Cannot find module 'decamelize'

mongodb - 使用 MongoDB 存储不可变数据?

javascript - 如何在保存另一个文档之前等待循环完成?

c++ - 最大子数组和 C++

node.js - 发送 MongoDB 数组以从 MongoDB 中的不同集合获取结果

arrays - Ruby Hash Values 是数组,需要转换成字符串