如何将节点API连接到本地计算机上的特定mongoDB db / collection

时间:2018-03-19 21:11:20

标签: node.js mongodb

之前可能已经提出这个问题,因为这个问题有多高,但是我找不到解决方案而且很难设置这个问题。我正在使用MERN堆栈处理我的第一个完整堆栈Web应用程序。我在Mac上。我在这里所做的一切都在我的本地机器上。

对于MongoDB ,我已将其安装在本地计算机上。我有mongod dameom运行。这是我在交互式mongo shell中的内容:

// run in terminal
> mongo

> show dbs
admin              0.000GB
config             0.000GB
mydboverhere       0.064GB
local              0.000GB

> use mydboverhere
switched to db mydboverhere

> show collections     
table_one
table_two
andathirdtable

我想将我的node / express API连接到 mydboverhere 数据库。在我的节点目录结构中,我有一个 models 目录:

/models/index.js

var mongoose = require('mongoose');
mongoose.set('debug', true);

// is this line correct? 
mongoose.connect('mongodb://localhost:27017/mydboverhere/table_one');

mongoose.Promise = Promise;
module.exports.Todo = require("./table1"); // this requires table1.js

/models/table1.js

// this matches the form of the data in the database, I believe 
var mongoose = require('mongoose');
var tab1Schema = new mongoose.Schema({
    name: { 
        type: String,
        required: 'cannot be blank'
    },
    completed: {
        type: Boolean,
        default: false
    },
    created_date: {
        type: Date,
        default: Date.now
    }
})

var Table1 = mongoose.model('Table1', tab1Schema)
module.exports = Table1;

我相信我的 / routes / tableroutes 文件正确无误:

var express = require('express');
var router = express.Router();
var db = require('../models')

router.get('/', function(req, res){
    // res.send("Hello from the table1 route")
    db.Table1.find()
        .then(function(data) {
            res.json(data);
        })
        .catch(function(err) {
            res.send(err);
        })
});

module.exports = router;

并且我认为我也正确地将这些路线加载到我的 root /index.js 文件中:

var express = require('express')
var app = express();

var tableRoutes = require('./routes/tableroutes');

// test the root route
app.get('/', function(req, res){
    res.send("Hello from the Root Route")
});

// set base route to /api for my tableRoutes    
app.use('/api', tableRoutes); 

app.listen(3000, () => console.log('Example app listening on port 3000!'))

不幸的是,在运行mongod时,当我尝试运行node index.js以使我的节点应用程序运行时,我在命令行中收到以下错误消息:

...(node:66245)UnhandledPromiseRejectionWarning:错误:不支持的主机&localhost:27017 / mydboverhere / table_one',主机必须是URL编码的,并且最多包含一个未编码的斜杠...

我现在就被困在这里......差不多,我不确定我是否正确连接我的节点API和mongodb。这一切都是在我的本地机器上完成的,我应该在/ data / db上安装mongodb。可能错误是由于集合名称table_one中的下划线。也许错误是因为mongo中table_one集合中的数据并不是因为与table1.js中的模式完全匹配(我通过将数据帧从R推入其中来单独创建mongodb,然后编写table1.js模式以匹配它)。

无论以上哪个问题问题,我都不确定,而且我很难继续。非常感谢任何帮助!

EDIT1:我强烈感觉到以下几行:

mongoose.connect('mongodb://localhost:27017/mydboverhere/table_one');

不正确,我看到了连接到特定数据库的正确方法。

EDIT2:我认为还有另一个名为mongoDB的javascript库,但我非常希望能够使用mongoose。

3 个答案:

答案 0 :(得分:1)

我认为这里有一个错误:

您使用的是thisdboverhere,而应该是mydboverhere

mongoose.connect('mongodb://localhost:27017/mydboverhere', function(){
 // do your process here
});

 mongoose.connect('mongodb://localhost:27017/mydboverhere');
  var db = mongoose.connection // I think you are forgetting to instantiate the connection here

答案 1 :(得分:0)

this good github post here,我发现了以下内容:

    El fichero está vacío
se ha creado una persona nueva con el nombre de:  Sandra
Traceback (most recent call last):
  File "Guardado_permanente.py", line 54, in <module>
    miLista.agregarPersonas(persona)
  File "Guardado_permanente.py", line 34, in agregarPersonas
    self.guardarPersonasEnFicheroExterno()
  File "Guardado_permanente.py", line 42, in guardarPersonasEnFicheroExterno
    pickle.dump(self.personas, listaDePersonas)
_pickle.PicklingError: Can't pickle <class '__main__.persona'>: it's not the same object as __main__.persona

***Repl Closed***

答案 2 :(得分:0)

我参加聚会很晚,但是我有同样的错误信息。删除数据库名称中的下划线已为我修复。

我尝试使用的原始数据库名称是:

const URL_MONGODB = "mongodb://localhost:27017/portfolio_db";

我删除了下划线,并使用了以下数据库名称:

const URL_MONGODB = "mongodb://localhost:27017/portfoliodb";

此后,我不再收到错误“ UnhandledPromiseRejectionWarning:错误:不支持的主机'localhost:27017 / data / db',主机必须经过URL编码,并且最多包含一个未编码的斜杠”