简体   繁体   English

mongojs驱动程序未连接到mongodb

[英]mongojs driver not connecting to mongodb

i have been trying to connect to my local mongodb using mongojs package but its not connecting at all. 我一直在尝试使用mongojs包连接到我的本地mongodb,但它根本没有连接。 i have my mongo service running on http://127.0.0.1:27017/ and below is my code : 我在http://127.0.0.1:27017/上运行了我的mongo服务,以下是我的代码:

    var express = require('express');
var app  = express();
var bodyParser = require('body-parser');
var mongo= require('mongojs');
var db=mongo('catalog',['products']);

app.use(bodyParser.json);
//adding our first route  name 
db.on('connect', function () {
    console.log('database connected')
})
app.get('/',function(req,res){
    res.send('It Worked');
});
app.get('/products',(req,res)=>{
    db.products.find(function (err,docs) {
        if (err) {
            res.json(err)
        }else{
            res.json(docs)
        }
    })
});

i have set event on connect to log if the connection is established but nothing is showing up.do you i could use mongoose or some other packages if it doesnt work at all? 我已在连接上设置了事件以记录日志(如果已建立连接),但是什么都没有显示出来。如果我根本无法使用猫鼬或其他软件包,我可以使用吗?

mongojs doesn't fire the connect function until you make the first request to a collection. 除非您对集合提出第一个请求, mongojs不会触发connect函数。 Make a request to your collection and the on('connect') function will fire. 向您的集合请求, on('connect')函数将触发。

Or in your case go to /products in your browser and you can see the database connected log in your terminal. 或者,在您的浏览器中转到/products ,您可以在终端中看到数据库连接日志。

If you want to request records from your collection without going to /products in your browser then just write your query outside of your app.get('/products') . 如果您想从集合中请求记录而无需在浏览器中访问/products ,则只需在app.get('/products')之外编写查询。

Make sure you add 确保您添加

app.listen(3000, function() { 
  console.log('server is running');
});

at the the end and go to localhost:3000/products in your browser. 最后,在浏览器中转到localhost:3000/products

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM