findOne有效,但无法获得全部/发现 [英] findOne works but not get all/find

查看:180
本文介绍了findOne有效,但无法获得全部/发现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

findOne正常工作

findOne works fine

db.collection('updates', function (err, collection) {
        collection.findOne({
            author: req.user._id
        }, function (err, doc) {
        }
 });

我正在尝试获取所有文档,而不仅仅是一份.我正在更改find​​One来查找(如下所示),但是它不起作用.我该如何解决?

I'm trying to get all the documents instead of just one. I'm changing findOne to find (shown below) and it doesn't work. How do I fix this?

        db.updates.find({
            author: req.user._id
        }, function (err, doc) {
        }

错误消息: 这是因为无法调用未定义的方法"find",这意味着无法识别该集合.

The error message: It's saying Cannot call method "find" of undefined, meaning the collection isn't being recognized.

更新: 这也不起作用:

Update: This doesn't work either:

db.collection('updates', function (err, collection) {
        collection.find({ //changed findOne to find
            author: req.user._id
        }, function (err, doc) {
        }
 });

推荐答案

您似乎正在使用本地MongoDB Node.JS驱动程序来查询您的数据库. 根据其自述文件,您应使用.toArray()方法实例化 MongoDB游标,从.find()调用返回:

It looks like you're using Native MongoDB Node.JS Driver to query your database. According to its readme, you should use .toArray() method to instantiate MongoDB cursor, returned from .find() call:

collection.find({
  author: req.user._id
}).toArray(function (err, docs) {
  // docs is an Array of documents here
});

如果您在使用本机MongoDB Node.JS驱动程序时遇到麻烦,建议您使用一些包装程序,使其具有更直观的API,例如:

If you have troubles with Native MongoDB Node.JS Driver, I would suggest using some wrapper around it with more intuitive API, e.g.:

  • mongojs
  • monk
  • mongoskin

这篇关于findOne有效,但无法获得全部/发现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆