Mongoose find() 不返回结果 [英] Mongoose find() not returning result

查看:65
本文介绍了Mongoose find() 不返回结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我设置了一个使用名为 Todo 的模型的路由,如下所示:

I have a route set up that uses a model called Todo like below:

app.get('/api/todos', function(req, res) {
    Todo.find({},function(err, todos) {
        if (err)
            res.send(err);
        console.log("number of todos " + todos.length);
        res.json(todos); // return all todos in JSON format
    });
});

然而,todos.length 总是 0,因为它没有找到任何结果.当我跑步时:

however, todos.length is always 0, as it do not find any results. When I run:

use test3
db.Todo.find() 

我确定我已经连接到同一个数据库.我可以在 mongod 控制台中看到连接.我的连接在 config/db.js 文件中:

I am sure I have connected to the same db. I can see the connection in mongod console. My connection is inside config/db.js file:

module.exports = {
    url : 'mongodb://localhost/test3'
}

我的server.js中的连接如下:

The connection in my server.js is as follows:

var db = require('./config/db');
mongoose.connect(db.url);

在 Mongo Shell 中我得到 1 个结果.我希望通过查找查询返回此结果.有什么我错过了吗?我正在使用猫鼬 3.6

in Mongo Shell I get 1 result. I am expecting this result to be return by the find query. Is there something I have missed? I am using Mongoose 3.6

干杯

推荐答案

所以这看起来很像您已经在现有数据库中创建了集合,现在您正在尝试使用 mongoose 模型访问这些集合.

So what this very much looks like is that you have already created collections in an existing database and now you are trying to access these with mongoose models.

问题在于 mongoose 使用了一些您可能不知道的默认值,因此您从 shell 中显示的示例与默认情况下 mongoose 所做的不同.

The problem is that mongoose uses some defaults which you may not be aware of, so the example you are showing from the shell is not the same as what mongoose is doing by default.

因此,您可以重命名您的集合以匹配默认情况下 mongoose 期望的内容,或者更改 mongoose 所做的内容以匹配您现有的名称.在后一种情况下,您可以像这样直接定义模型名称:

So you can either rename your collections to match what mongoose expects by default or change what mongoose does to match your existing names. In the latter case, you directly define the model names like so:

mongoose.model( "Todo", toDoSchema, "Todo" );

所以 方法 的第三个参数实际上指定了用于集合的显式名称.如果没有这个,默认规则下的假定名称将是todos".

So the third argument to the method actually specifies the explicit name to use for the collection. Without this the assumed name under the default rules will be "todos".

使用任何一种方法使它们匹配.

Use either method in order yo make them match.

这篇关于Mongoose find() 不返回结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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