简体   繁体   中英

Mongoose Fails to retrieve documents

I am learning MongoDB+Mongoose+Express right now. And I am facing a bug I can't figure out myself.

My MongoDB setup (A DB with 2 collections, each has some documents): 具有2个集合的DB,每个集合都有一些文档

app.js connection to a database:

const dbConnectionString = process.env.MONGODB_URI || 'mongodb://localhost';
mongoose.connect(dbConnectionString + '/blog');

posts.js model:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var PostsSchema = new Schema({
    any: {}
});

var Posts = mongoose.model('Posts', PostsSchema);

module.exports = Posts;

blog.js route:

var express = require('express');
var router = express.Router();
var Posts = require('../models/posts')

router.get('/', function(req, res, next) {
  console.log('Route works');
  console.log(Posts);
  Posts.find((err,posts) => {
    if( err ) return console.log('DB Error', err);
    console.log('Posts Received', posts);
    res.render('blog', { title: 'My Blog', posts : posts });  
  });
});

module.exports = router;

when I run mongodb and node server, accessing it successfully console.logs Schema and

Route works
Posts Received []

So while the connection to a database seem to work(I don't get errors) I can't get the data from it. I know that I am missing something obvious due to the lack of knowledge but my search through mongoose docs didn't help. Please advise and thank you for your help!

The problem is that you are not passing any object to find.

The find function in mongoose requires a query parameter. If you need to retrieve the whole collection, you can pass an empty object:

MongooseSchema.find({},callback)

The first object is the query. You can use some selectors there too. For example, let's say you want everyone with a determined title, in that case you can do something like:

MongooseSchema.find({title:"title"},callback)

For more than one query parameter, you can separate by commas:

MongooseSchema.find({title:"title",subtitle:"subtitle"},callback)

and so on. I recommend you taking a look at the mongoose manual part on this matter:

http://mongoosejs.com/docs/queries.html

[Update]

The problem in this case was that mongoose naming conventions were not matching the names used by you. Mongoose does queries in lower-case names, and in this case did not find the Posts collection because of the upper-case P in the beginning of the name. It was solved by changing by 'posts', all in lower-case.

Just a second reminder, mongoose also pluralizes the names when creating collections, so one should be also aware of this fact when creating collections in mongodb.

Reference by @veeram: http://mongoosejs.com/docs/guide.html#collection

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM