使用printjson()打印字段时如何删除_id?

时间:2019-06-01 07:36:23

标签: javascript json mongodb mongojs

db.events.find().forEach(function(doc)
{
    var iso_date = new Date(doc.starts_at);
    if(iso_date>= new Date() && iso_date<= new Date(new Date().setDate(new 
     Date().getDate()+4))){
        printjson(doc);
    }
})

我无法在MongoDB中使用_id删除printjson()字段。我正在根据使用JavaScript处理的特定条件打印字段。使用printjson()打印时,无法删除_id字段。使用_id进行打印时,是否可以删除printjson()

2 个答案:

答案 0 :(得分:0)

正如JME在您的问题的注释中指出的那样,您可以在打印文档之前删除_id字段。另一方面,日期的比较可能更简单一些,更重要的是,您应该在查询中执行此操作,以便仅处理所需的文档,而不是遍历数据库中的所有文档,因此我认为您的代码看起来可以像这样:

db.events.find({starts_at: {$gte: Date.now(), $lte: new Date().setDate(4)}}).forEach(function(doc)
{
    delete doc._id;
    printjson(doc);
});

答案 1 :(得分:0)

只需使用projection即可避免在数据库结果中返回_id:

db.events.find(
  {starts_at: {$gte: Date.now(), $lte: new Date().setDate(4)}},
  {_id:0} 
)
.forEach(function(doc)
{
    printjson(doc);
});
相关问题