如何从mongodb获取数据并使用node.js显示

时间:2022-12-02 02:33:58

Following is my code to fetch data from a collection and show it on index page, but it is not giving the results.

以下是我从集合中获取数据并在索引页面上显示它的代码,但它没有给出结果。

Node Code-

节点代码 -

var app = require('express')();
var mongoose = require('mongoose');
var dbURI = 'mongodb://localhost/test';

mongoose.connect(dbURI);
var testSchema = new mongoose.Schema({
        name: String,
        rollnum: String
});

var Test = mongoose.model('Test', testSchema);

app.get('/', function(req, res){
        Test.find({},function(err, docs){
                res.send('index',{docs:docs});
        });
        //res.send('test');
});

app.listen(3001);

However I check and have a collection in db like this -

但是我检查并在db中有一个像这样的集合 -

Query fire - db.testinfo.find()

查询fire - db.testinfo.find()

Output -

输出 -

{
"_id": ObjectId("123456..78"),
"name": "test",
"rollnum": "XXXX"
}

After hitting the URL - http://127.0.0.1:3001/

点击URL后 - http://127.0.0.1:3001/

This is the output I am getting -

这是我得到的输出 -

{
  "docs": []
}

However I was expecting to get the result of name, rollnum.

但是我期待得到名字的结果,rollnum。

Please let me know what I am doing wrong.

请让我知道我做错了什么。

1 个解决方案

#1


3  

When you register a model in Mongoose, it uses the pluralized, lower-cased model name as the name of the collection it's tied to. So because your model name is Test, the collection name is tests.

当您在Mongoose中注册模型时,它使用复数的,较低的模型名称作为它所绑定的集合的名称。因此,因为您的模型名称是Test,所以集合名称是test。

To tie the model to testinfo instead, pass that name as the third parameter to your model call:

要将模型绑定到testinfo,请将该名称作为第三个参数传递给模型调用:

var Test = mongoose.model('Test', testSchema, 'testinfo');

#1


3  

When you register a model in Mongoose, it uses the pluralized, lower-cased model name as the name of the collection it's tied to. So because your model name is Test, the collection name is tests.

当您在Mongoose中注册模型时,它使用复数的,较低的模型名称作为它所绑定的集合的名称。因此,因为您的模型名称是Test,所以集合名称是test。

To tie the model to testinfo instead, pass that name as the third parameter to your model call:

要将模型绑定到testinfo,请将该名称作为第三个参数传递给模型调用:

var Test = mongoose.model('Test', testSchema, 'testinfo');