Mongoose JS查询所有返回null或空 [英] Mongoose JS queries all coming back null or empty
问题描述
我正在尝试创建一个简单的MongooseJS示例程序,该程序从集合中获取项目列表,并且每次都会返回空白。以下是代码:
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
});
});
我有一个默认的MongoDB运行实例,这就是我在shell中输入的内容:
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?
感谢您的帮助,
Dave
Thanks for your help, Dave
推荐答案
mongoose
会将集合名称规范化为小写和复数。因此,您应该插入 db.samplecollections
而不是 db.sampleCollection
。 (注意字母 c
和 s
的区别)。
mongoose
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
here).
测试它:
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中:
then in mongo shell:
> show collections
samplecollections //<<<<<<<<<<<<<< It's all lowercase and pluralized
system.indexes
> db.samplecollections.find()
{ "sampleField" : "hello", "_id" : ObjectId("4f28ab4cc9e58f710a000001") }
这篇关于Mongoose JS查询所有返回null或空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!