Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
471 views
in Technique[技术] by (71.8m points)

javascript - Mongoose find() not returning result

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
    });
});

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

use test3
db.Todo.find() 

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'
}

The connection in my server.js is as follows:

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

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

Cheers

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

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" );

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...