Todas las consultas de Mongoose JS vuelven nulas o vacías

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

preguntado el 01 de febrero de 12 a las 01:02

2 Respuestas

mongoose will normalize the name of collection to lowercase and pluralzed. Therefore, you should insert into db.samplecollections en lugar de db.sampleCollection. (Notice the difference of letter c y s aquí).

para probarlo:

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

and it properly prints:

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

then in mongo shell:

> show collections
samplecollections          //<<<<<<<<<<<<<< It's all lowercase and pluralized
system.indexes

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

Respondido 01 Feb 12, 07:02

Wow! Thanks for your help, that makes sense now. Why on earth does the mongoose documentation not mention that? mongoosejs.com Seems like a huge gap in the documentation... - Dave Morris

Wait, you used mongoose and documentation in the same comment? Bwahahahaha! - AlbertEngelB

That was exactly it for me! Thanks @qiao - janex

While this is true, you can specify the name of the collection in the third argument and it will use the case from that string:

var sampleCollection = mongoose.model('sampleCollection', sampleSchema,'SampleCollection');

respondido 22 mar '13, 03:03

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.