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

查看:96
本文介绍了猫鼬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个结果.我期望此结果将由find查询返回. 有什么我想念的吗? 我正在使用Mongoose 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

欢呼

推荐答案

因此,这非常像是您已经在现有数据库中创建了集合,现在您正尝试使用猫鼬模型访问这些集合.

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.

问题是猫鼬使用了一些您可能不知道的默认值,因此您从shell中显示的示例与猫鼬默认情况下的操作不同.

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.

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

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.

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

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