0

我有一个有属性的模型

_idUserReadArr //  array of users who have read an article

这将是一个巨大的阵列。

我希望我的 API 返回一个布尔值

isRead

_idUserReadArr如果包含特定的 id,则应该为 true ,在其他情况下为 false。

所以,而不是

_idUserArr = [1, 2, 3]

我想获取isRead = trueisRead = false不返回或直接使用大_idUserReadArr数组进行一些操作。

我正在使用 mongoose 处理 node.js。

4

1 回答 1

1

不使用聚合框架,您无法更改输出的性质,但使用简单的包装器,您可以非常接近。在这种情况下,确实没有必要使用聚合框架,因为这种解决方案既简单又高效。

当您指定find所需的内容时,只需将结果限制为单个字段(如_id)。

http://mongoosejs.com/docs/api.html#model_Model.find

myModel.find({ ... condition ... }, "_id", function(err, docs) {
   // the existence of the doc means your condition was true
   // without sending back the entire document/array structure
});

findOne也具有相同的功能findXYZ(与Mongoose中的其他几个功能一样)。

MongoDB 对投影的本机支持支持此功能,如此所述。

于 2013-09-03T13:42:28.457 回答