如何使用mongoose从MongoDb获取数据? [英] How to get Data from MongoDb using mongoose?
问题描述
我刚刚开始学习MongoDB和mongoose。目前我有以下结构:
I just started learning MongoDB and mongoose. Currently I have the following structure:
database -> skeletonDatabase
collection -> adminLogin
当我运行 db.adminLogin.find()
从命令行我得到:
When I run db.adminLogin.find()
from the command line I get:
{ "_id" : ObjectId("52lhafkjasfadsfea"), "username" : "xxxx", "password" : "xxxx" }
我的连接
module.exports = function(mongoose)
{
mongoose.connect('mongodb://localhost/skeletonDatabase');
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function callback () {
console.log('Conntected To Mongo Database');
});
}
我的-js -
module.exports = function(mongoose)
{
var Schema = mongoose.Schema;
// login schema
var adminLogin = new Schema({
username: String,
password: String
});
var adminLoginModel = mongoose.model('adminLogin', adminLogin);
var adminLogin = mongoose.model("adminLogin");
adminLogin.find({}, function(err, data){
console.log(">>>> " + data );
});
}
我的 console.log()
返回为>>>>
那么我在这里做错了什么?为什么我的控制台日志中没有任何数据?提前感谢任何帮助。
So what am I doing wrong here? Why do I not get any data in my console log? Thanks in advance for any help.
推荐答案
mongoose默认情况下会使用单个模型名称,并将它们与以复数形式命名的集合那么,所以mongoose在数据库中查找一个不存在的名为adminLogins的集合。您可以在定义模式时将集合名称指定为第二个参数:
mongoose by default takes singular model names and pairs them with a collection named with the plural of that, so mongoose is looking in the db for a collection called "adminLogins" which doesn't exist. You can specify your collection name as the 2nd argument when defining your schema:
var adminLogin = new Schema({
username: String,
password: String
}, {collection: 'adminLogin'});
这篇关于如何使用mongoose从MongoDb获取数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!