Mongoose always returning an empty array NodeJS

后端 未结 5 1023

I have tried using find and findOne and both are not returning a document. find is returning an empty array while findOne

相关标签:
5条回答
  • 2020-11-22 10:27

    This issue is probably coming from the fact that you are creating a mongoose model without specifying the name of the collection.

    Try changing : const Model = mongoose.model("Model", fileSchema);

    To this : const Model = mongoose.model("Model", fileSchema, "NameOfCollection");

    0 讨论(0)
  • 2020-11-22 10:38

    The call to mongoose.model establishes the name of the collection the model is tied to, with the default being the pluralized, lower-cased model name. So with your code, that would be 'models'. To use the model with the files collection, change that line to:

    var Model = mongoose.model("Model", fileSchema, "files");
    

    or

    var Model = mongoose.model("file", fileSchema);
    
    0 讨论(0)
  • 2020-11-22 10:40

    Simply inorder to avoid pluralization complexity use this:

    var Model = mongoose.model("Model", fileSchema, "pure name your db collection");
    

    It's very confusing.[at least for me.]

    0 讨论(0)
  • 2020-11-22 10:47
    const growingUnit= mongoose.model('Growing Unit', growingUnitSchema);
    

    I had a space in 'Growing Unit' on purpose and it always returned empty array. Removing that space to become 'GrowingUnit' was the fix needed in my scenario.

    const growingUnit= mongoose.model('Growing Unit', growingUnitSchema);
    
    0 讨论(0)
  • Had kinda same problem. The solutions above didnt work for me. My app never returns error even if the query is not found. It returns empty array. So i put this in my code:

    if(queryResult.length==0) return res.status(404).send("not found");
    
    0 讨论(0)
提交回复
热议问题