-2

I have a problem with NodeJS and Mongoose. The connection to the DB stands but I can't get any data from there. I can connect to /api/buckets as well with no problems. Here is my code:

app.js

var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var mongoose = require('mongoose');

Bucket = require('./models/bucket');

// Connect to Mongoose
mongoose.connect('mongodb://localhost/worldbucket', function (err) {
    if (err) throw err;
    console.log('Successfully connected');
});


app.get('/', function (req, res) {
    res.send('Please use sth other');
});

app.get('/api/buckets', function (req, res) {
    Bucket.getBuckets(function (err, buckets) {
        console.log("funkt");
        if (err) {
            throw err;
        }
        res.json(buckets);
    });
});

app.listen(3000);
console.log('Running on port 3000');

and bucket.js:

var mongoose = require('mongoose');

// Bucket Schema
var bucketSchema = mongoose.Schema({
    id: mongoose.Schema.Types.ObjectId,
    creator: String,
    text: String,
    fulfilment: String,
    latitude: Number,
    longtitude: Number
});

var  Bucket = mongoose.model('bucket', bucketSchema);

module.exports = Bucket;

// get Buckets
module.exports.getBuckets = (callback, limit) => {
    Bucket.find(callback).limit(limit);
}

I hope you can help me.

Thanks in advance

robjwilkins
  • 5,462
  • 5
  • 43
  • 59
N. Richli
  • 102
  • 1
  • 10

2 Answers2

1

Im not sure what version of mongoose you using, but from their docs

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

// With a JSON doc
  Person
      .find({
        occupation: /host/
      })
      .limit(10)
      .sort({ occupation: -1 })
      .select({ name: 1, occupation: 1 })
      .exec(callback);

So in your case should be

Bucket.find({}).limit(limit).exec(callback);

Hope this helps.

Grynets
  • 2,477
  • 1
  • 17
  • 41
Mykola Borysyuk
  • 3,373
  • 1
  • 18
  • 24
0

Check the name of your collection in mongo - it should be called buckets not bucket. It needs to be plural. Apart from that your code works, I have tested it.

> db
worldbucket
> db.buckets.insert({"creator":"me","text":"hello world"})
WriteResult({ "nInserted" : 1 })
> db.buckets.find()
{ "_id" : ObjectId("5a0a154a29642fd7a970420e"), "creator" : "me", "text" : "hello world" }


$ curl http://localhost:3000/api/buckets
[{"_id":"5a0a154a29642fd7a970420e","creator":"me","text":"hello world"}]

There is another SO thread on this topic here: Why does mongoose always add an s to the end of my collection name

robjwilkins
  • 5,462
  • 5
  • 43
  • 59