Model.find()在mongoose中返回空 [英] Model.find() returns empty in mongoose
问题描述
我正在处理mongoose,从mongodb中的数据库中收集所有数据:
i am working upon mongoose to list all the data from a collection in a db in mongodb:
来自请求:
http://localhost:3000/listdoc?model=Organization
我正在执行以下代码:
exports.listDoc = function(req, res) {
var Model = mongoose.model(req.query.model); //This is defined and returns my desired model name
Model.find().populate('name').exec(function(err, models) {
if (err) {
res.render('error', {
status: 500
});
} else {
res.jsonp(models);
}
});
};
我已经在数据库
中输入了条目但上述代码返回空。为什么?
I already have my entry in database But the above code returns empty. Why?
编辑:以下代码也返回空:
EDIT : the following code also returns empty:
exports.listDoc = function(req, res) {
var Model = mongoose.model(req.query.model);
Model.find({},function(err,models){
console.log(models);
if (err) {
res.render('error', {
status: 500
});
} else {
res.jsonp(models);
}
});
};
使用模式:
var Organization = mongoose.Schema({
name: String
});
推荐答案
您的问题是mongoose多元化集合。 Mongoose正在查询组织,但您的数据在mongodb中是组织。让他们匹配,你应该很好去。您可以通过mongo shell在mongodb中重命名它,也可以告诉mongoose。从mongoose文档:
Your problem is mongoose pluralizes collections. Mongoose is querying "organizations" but your data is in mongodb as "organization". Make them match and you should be good to go. You can either rename it in mongodb via the mongo shell or tell mongoose about it. From the mongoose docs:
var schema = new Schema({ name: String }, { collection: 'actor' });
// or
schema.set('collection', 'actor');
// or
var collectionName = 'actor'
var M = mongoose.model('Actor', schema, collectionName)
这篇关于Model.find()在mongoose中返回空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!