简体   繁体   中英

Can't seem to display data from mongolab using node.js

i'm been trying to display just a simple data from mongolab to nodejs and it displays nothing for some reason.

var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
mongoose.connect("mongodb://db-user:pass@ds049084.mongolab.com:49084/mydb");
mongoose.model('collection',{ name:String });

router.get('/', function(req, res, next) {
  mongoose.model('collection').find({},function(err,docs){
     res.send(docs);
  });
});

I've already saved a name data in the document of the collection in mongolab, the only it shows when i run the debug script debug=mynode:* npm start is []

does anybody know why is that? thank you.

Fixed it!, man..the problem is the way i named the collections at mongolab. I was missing the "s" at the end of collection. Once i deleted the collection and created another but this time the "s" at the end, then it worked.

eg Naming a collection 'Car' will not work but naming it 'cars' will work somehow

I can't comment yet because of my rep... But to elaborate.. The reason why you need the "s" at the end is because when you do:

mongoose.model('<the schema you want to map to in your db>',<yourschema>);

"Mongoose automatically looks for the plural version of your model name" in your db.. as it says in the Mongoose documentation.. hence if you type myDbSchema it would look for myDbSchemas (Note the "s") and so thats why in your mongolabs Db the schema would need the extra "s"... confused me for a bit to but I hope this can help someone! :) as this post did help me too.

FYI Mongoose documentation: Mongoose Models Doc

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