如何在节点js中使用猫鼬?

时间:2019-08-18 09:36:06

标签: node.js mongoose

我是Node JS的初学者,在这里我试图连接到MongoDB。

我正在关注一个教程,在此基础上,我具有以下项目结构:

- server
  - config
    - db.js
  - index.js
- index.js

我的猫鼬依赖版本为:5.6.9

在我的db.js中,我有以下几行代码:

const mongoose = require('mongoose');

// connection to mongoose
export default () => {
    mongoose.connect('mongodb://localhost/dbCollection', function(err, db) {
        if (err) {
            console.log('Unable to connect to the server. Please start the server. Error:', err);
        } else {
            console.log('Connected to Server successfully!');
        }
    });
}

在服务器文件夹中的index.js中,我有

import express from 'express';
import dbConfig from './config/db';

const app = express();
dbConfig();

但是我遇到了错误

 _mongoose2.default.connection().once('open', function () {
                       ^

TypeError: _mongoose2.default.connection is not a function
    at exports.default 

2 个答案:

答案 0 :(得分:1)

尝试一下:

const mongoose = require('mongoose');

const connect = mongoose.connect("mongodb://localhost:27017/dbCollection");

connect.then((db) => {
    console.log('Connected correctly to server');
}, (err) => {
    console.log(err)
    // next(err)
});

答案 1 :(得分:0)

数据库连接并监听端口

// import dependencies
import express from 'express';
import bodyParser from 'body-parser';
import mongoose from 'mongoose';
import logger from 'morgan';// set up dependencies
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false });
app.use(logger('dev'));// set up mongoose

mongoose.connect('mongodb://localhost/projectsupport')
  .then(()=> {
    console.log('Database connected');
  })
  .catch((error)=> {
    console.log('Error connecting to database');
  });

// set up port
    const port = 5035;// set up route
    app.get('/', (req, res) => {
      res.status(200).json({
        message: 'Welcome to Project Support',
      });
    });app.listen(port, () => {
      console.log(`Our server is running on port ${port}`);
    });