2017-07-17 48 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