2017-07-17 49 views
0

我有一個名爲Collector的數據庫的MongoDB安裝,它包含一個名爲Msg的集合。 當我用mongo shell查看它時,我得到65個結果。集合存在,但Mongoose查詢返回空集

然而,查詢時使用的MongoDB貓鼬下面的代碼我得到一個空集:

var Msg = mongoose.model('Msg', { 
    process: String 
    // omitted fields 
}); 

server.use(express.static('./client')); // Serve the client 

server.use(function(req, res, next) { 
    res.header("Access-Control-Allow-Origin", "*"); 
    res.header("Access-Control-Allow-Headers", 
       "Origin, X-Requested-With, Content-Type, Accept"); 
    next(); 
}); 

// Return to the client a JSON object containing *ALL* msgs 
server.get('/msgs', function(req, res) { 
    Msg.find().exec(function(err, msgs) { 
     log(`err: ${err}`); 
     log(`/msgs => Found ${msgs.length} msgs`); 
     res.json(msgs); 
    }); 
}); 

一切似乎都不錯,但它不工作:參觀localhost:3000/msgs產生一個空的結果對象。那麼這個代碼有什麼問題?

回答

1

原來問題出在集合的名稱上:我已經命名爲Msg,而顯然如果模型名稱爲Msg,Mongo在默認情況下會查找Msgs。此處的解決方案是在模型調用中添加第三個參數:

var Msg = mongoose.model('Msg', { 
    process: String 
    // omitted fields 
}, 'Msg'); // <-- collection name