无法连接到mongo db node.js(未定义客户端)

时间:2018-02-25 15:24:35

标签: javascript node.js mongodb

我是node.js的初学者,并尝试构建一个基本的CRUD应用程序。但是我似乎无法连接到mongo db。这是我得到的错误

ReffernceError:未定义CLient。 在MongoClient.connect(C:/ user / User / desktop / blog app.js 在args.push

非常感谢任何帮助!!

const express = require('express');
const bodyParser= require('body-parser')
const app = express()


app.use(bodyParser.urlencoded({extended: true}))


const MongoClient = require('mongodb').MongoClient
var db

MongoClient.connect('mongodb://user:pass@ds029466.mlab.com:29466/movie-quotes', (err, database) => {
  // ... start the server

   if (err) return console.log(err)
 db = client.db('movie-quotes')
  app.listen(process.env.PORT || 3000, () => {
    console.log('listening on 3000')
  })
})


app.get('/', (req, res) => {
  res.sendFile(__dirname + '/index.html')
  // Note: __dirname is directory that contains the JavaScript source code. Try logging it and see what you get!
  // Mine was '/Users/zellwk/Projects/demo-repos/crud-express-mongo' for this app.
})


app.post('/quotes', (req, res) => {
  db.collection('quotes').save(req.body, (err, result) => {
    if (err) return console.log(err)

    console.log('saved to database')
    res.redirect('/')
  })

})

1 个答案:

答案 0 :(得分:1)

database是您的数据库客户端。你应该使用:

db = database.db('movie-quotes')

而不是:

db = client.db('movie-quotes')