I am trying to create a simple MongooseJS example program that gets a list of items from a collection, and it’s coming back empty every time. Here is the code:
var mongoose = require('mongoose')
, Schema = mongoose.Schema;
var sampleSchema = new Schema({
sampleField : String
});
var db = mongoose.connect('mongodb://localhost:27017/test');
var sampleCollection = mongoose.model('sampleCollection', sampleSchema);
sampleCollection.find({ } , function (err, items) {
console.log(items); // outputs []
console.log(err); // outputs null
items.forEach( function(item) {
console.log(item); // does not reach this code
});
});
I have a default instance of MongoDB running, and this is what I’ve entered in the shell:
> use test
> db.sampleCollection.save({sampleField : "Hello"});
> db.sampleCollection.save({sampleField : "Goodbye"});
> db.sampleCollection.find({});
{ "_id" : ObjectId("4f28944b38b59225012109da"), "sampleField" : "Hello" }
{ "_id" : ObjectId("4f28945138b59225012109db"), "sampleField" : "Goodbye" }
Any idea why my code doesn’t return any data?
Thanks for your help,
Dave
mongoosewill normalize the name of collection to lowercase and pluralzed. Therefore, you should insert intodb.samplecollectionsinstead ofdb.sampleCollection. (Notice the difference of lettercandshere).to test it:
and it properly prints:
then in mongo shell: