node.js - mongoDB查询返回null,但使用.toArray返回数据

标签 node.js mongodb

我在 mongoDB 中有这个查询

var query = { "_id": new ObjectID(id)};
var items = {items:1};

warehouses.find(query, items,function (error, docs) {
    if (error) {
       error(error);
       return;
    }


    success(docs);
});

我想通过 _id 从文档中获取项目。这返回给我 docs.items = undefined

但是当我这样做时:

warehouses.find(query, items).toArray(function (error, docs) {
            if (error) {
                error(error);
                return;
            }


            success(docs);
    });

返回数据:

0: Object
_id: ObjectID
items: Array[3]
0: Object
1: Object
2: Object
length: 3

如何通过第一个查询获取数据?我想要类似的东西

最佳答案

有一个很大差异。如果您只期望一个结果,例如通过_id搜索,则使用.findOne() :

warehouses.findOne(query, items, function (error, doc) {

否则您将返回 Cursor()目的。至少在 native 驱动程序中如此,在 ODM 中以某种形式如此。

关于node.js - mongoDB查询返回null,但使用.toArray返回数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22353358/

相关文章:

node.js - MongoDB 查询可以在 Mongo Shell 中工作,但不能在 Node.js 中工作?

node.js - 使用 Mognodb 和 Node.js 聚合函数返回空白数组值

javascript - Object.defineProperty 有时会抛出异常

session - 如何覆盖 node.js 快速 session 的 session ID(使用护照)

javascript - NODE.js无法使用reSTLer获得的restful数据

python - 最新的 django-mongodb-engine

javascript - MongoDB + Node JS + 基于角色的访问控制 (RBAC)

javascript - 将新密码添加到 ssh2-stream

javascript - 类型错误 : Cannot read property 'split' of undefined in Nodejs

java - 通过在一个集合中进行更改来反射(reflect)多个 mongodb 集合中的更改