Mongoose JS queries all coming back null or empty

前端 未结 2 2022
别跟我提以往
别跟我提以往 2021-02-08 22:45

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:

         


        
2条回答
  •  夕颜
    夕颜 (楼主)
    2021-02-08 23:24

    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).

    to test it:

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

提交回复
热议问题