Mongoose 检索没有 _id 字段的数据

新手上路,请多包涵

我想从我的 Node.js 应用程序中的 Mongoose 设置中检索一些数据。我注意到无论我写什么作为字段选择,我总是得到 _id 字段。有办法不取吗?这就是我现在的做法:

 Transaction.find({username : user.username}, ['uniqueId', 'timeout', 'confirmation_link', 'item_name'], function(err, txs){
        console.log("user : " + user.username + " with txs: " + txs);
        callback(txs);
});

并记录包含 _id 字段的结果。

原文由 Masiar 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 400
2 个回答

_id 必须明确排除。例如,

 Transaction.find({username : user.username}, { '_id': 0, 'uniqueId' :1, 'timeout': 1, 'confirmation_link': 1, 'item_name': 1}, function(err, txs){
  console.log("user : " + user.username + " with txs: " + txs);
  callback(txs);
});

原文由 danmactough 发布,翻译遵循 CC BY-SA 3.0 许可协议

另一种方法是使用带有前缀 - 的文本参数,这将从结果中排除这个或那个字段:

 Entity.find({ ... }, '-_id field1 field2', function(err, entity) {
    console.log(entity);  // { field1: '...', field2: '...' }
});

原文由 VisioN 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题