Mongoose JS查询所有返回null或空

时间:2012-02-01 01:27:08

标签: javascript node.js mongodb mongoose

我正在尝试创建一个简单的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中输入的内容:

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

知道我的代码为什么不返回任何数据?

感谢您的帮助, 戴夫

2 个答案:

答案 0 :(得分:12)

mongoose会将集合名称规范化为小写和复数。因此,您应该插入db.samplecollections而不是db.sampleCollection。 (请注意此处cs字母的差异。

测试它:

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

答案 1 :(得分:3)

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

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