Mongoose JS queries all coming back null or empty

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
>{sampleField : "Hello"});
>{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

Problem courtesy of: Dave Morris


will normalize the name of collection to lowercase and pluralzed. Therefore, you should insert into db.samplecollections
instead of db.sampleCollection
. (Notice the difference of letter c
and s

to test it:

s = new sampleCollection({sampleField: 'hello'}); // creates a new record { 
  sampleCollection.find({ } , function (err, items) {
      items.forEach( function(item) {

and it properly prints:

[ { sampleField: 'hello', _id: 4f28ab4cc9e58f710a000001 } ]
{ sampleField: 'hello', _id: 4f28ab4cc9e58f710a000001 }

then in mongo shell:

> show collections
samplecollections          //<<<<<<<<<<<<< db.samplecollections.find()
{ "sampleField" : "hello", "_id" : ObjectId("4f28ab4cc9e58f710a000001") }

Solution courtesy of: qiao

Node.js Recipes责编内容来自:Node.js Recipes (源链) | 更多关于

本站遵循[CC BY-NC-SA 4.0]。如您有版权、意见投诉等问题,请通过eMail联系我们处理。
酷辣虫 » 前端开发 » Mongoose JS queries all coming back null or empty

喜欢 (0)or分享给?

专业 x 专注 x 聚合 x 分享 CC BY-NC-SA 4.0

使用声明 | 英豪名录