【问题标题】:NodeJS Mongoose not working properlyNodeJS Mongoose 无法正常工作
【发布时间】:2018-04-26 16:27:54
【问题描述】:

我对 NodeJS 和 Mongoose 有疑问。与数据库的连接仍然存在,但我无法从那里获取任何数据。我也可以毫无问题地连接到 /api/buckets。这是我的代码:

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

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

我希望你能帮助我。

提前致谢

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    我不确定您使用的是什么版本的猫鼬,但来自他们的文档

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

    所以在你的情况下应该是

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

    希望这会有所帮助。

    【讨论】:

      【解决方案2】:

      在 mongo 中检查您的集合的名称 - 它应该称为 buckets 而不是 bucket。它必须是复数。除了您的代码有效之外,我已经对其进行了测试。??

      > 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"}]
      

      这里有关于这个主题的另一个 SO 线程:Why does mongoose always add an s to the end of my collection name

      【讨论】: