Mongoose JS查询全部返回null或空

我正在尝试创build一个简单的MongooseJS示例程序,该程序从集合中获取项目列表,并且每次都会回到空白处。 这里是代码:

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

我有一个运行MongoDB的默认实例,这就是我在shell中input的内容:

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

任何想法为什么我的代码不会返回任何数据?

感谢您的帮助,Dave

mongoose会将收集的名字规范化为小写字母和复数forms。 因此,您应该插入db.samplecollections而不是db.sampleCollection 。 (注意这里的字母cs的区别)。

testing它:

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

并正确打印:

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

那么在mongo shell中:

 > show collections samplecollections //<<<<<<<<<<<<<< It's all lowercase and pluralized system.indexes > db.samplecollections.find() { "sampleField" : "hello", "_id" : ObjectId("4f28ab4cc9e58f710a000001") } 

虽然这是真的,但您可以在第三个参数中指定集合的​​名称,并使用该string的大小写:

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