簡體   English   中英

Mongoose 總是返回一個空數組 NodeJS

[英]Mongoose always returning an empty array NodeJS

我曾嘗試使用findfindOne ,但都沒有返回文檔。 find返回一個空數組,而findOne返回null err在這兩種情況下null為好。

這是我的連接:

function connectToDB(){
    mongoose.connect("mongodb://localhost/test"); //i have also tried 127.0.0.1
    db = mongoose.connection;
    db.on("error", console.error.bind(console, "connection error:"));
    db.once("open", function callback(){
        console.log("CONNECTED");
    });
};

這是我的架構:

var fileSchema = mongoose.Schema({
    hash: String,
    type: String,
    extension: String,
    size: String,
    uploaded: {type:Date, default:(Date.now)},
    expires: {type:Date, default:(Date.now()+oneDay)}
});
var Model = mongoose.model("Model", fileSchema);

我的查詢在這里:

Model.find({},function(err, file) {
    console.log(err)
    console.log(file);  
});

我可以將內容上傳到數據庫並通過RockMongo查看它們,但之后我無法獲取它們。 這是我第一次使用 MongoDB,所以我想我只是缺少一些基礎知識。 任何朝着正確方向的推動都會很棒!

mongoose.model的調用建立了模型所關聯的集合的名稱,默認是復數的小寫模型名稱。 所以用你的代碼,那將是'models' 要將模型與files集合一起使用,請將該行更改為:

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

或者

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

簡單地為了避免復數復雜性使用這個:

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

這很令人困惑。[至少對我來說。]

有一點同樣的問題。 上面的解決方案對我不起作用。 即使找不到查詢,我的應用程序也永遠不會返回錯誤。 它返回空數組。 所以我把它放在我的代碼中:

if(queryResult.length==0) return res.status(404).send("not found");

這個問題可能是因為您正在創建一個貓鼬模型而沒有指定集合名稱

嘗試改變: const Model = mongoose.model("Model", fileSchema);

對此: const Model = mongoose.model("Model", fileSchema, "NameOfCollection");

const growingUnit= mongoose.model('Growing Unit', growingUnitSchema);

我故意在“增長單元”中有一個空間,它總是返回空數組。 刪除該空間以成為“GrowingUnit”是我的場景中需要的修復。

const growingUnit= mongoose.model('Growing Unit', growingUnitSchema);

一般的“hello world”問題(有時這個問題與貓鼬無關)。

  1. 檢查集合是否真的為空( mongoDB atlas截圖)。

在此處輸入圖片說明

  1. 檢查集合查詢命令中的小的拼寫差異(如listing而不是listings )。

  2. 檢查您的連接是否使用了正確的URI (例如,您嘗試從localhost中存在的集合中檢索數據,但使用mongoDB cluster (雲)-或-與連接字符串 URI 相關的任何其他問題)。https://docs.mongodb.com/manual/reference/connection-string/

對我來說,問題是.skip(value) ,我傳遞的是page=1而不是page=0 由於我的記錄很少,我總是得到空數組。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM