Good afternoon, I just started learning Node.JS, so don’t be strict) I’m trying to create an application with data exchange with the MongoDB database, but I can’t execute a POST request to the database.
An error occurs
TypeError: db.collection is not a function
And for some reason in the console writes
connection accepted from 127.0.0.1 Oc1061 # 4 (1 connection now open)
That is the wrong port.
var express = require('express'); var app = express(); var bodyParser = require('body-parser'); var MongoClient = require('mongodb').MongoClient; var db = null; app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); app.get('/user',function(req, res){ res.send(users); }) app.post('/user',function(req, res){ var user = { login: req.body.login }; db.collection('users').insert(user, function(err, result){ if(err){ console.log(err); return res.sendStatus(500); }; res.send(user); db.close(); }) res.send(user); }) MongoClient.connect('mongodb://localhost:27017/chat_bd', function(err, database){ if(err){return console.log(err)} db = database; app.listen(4040, function(){ //in 4040 port(http://localhost:4040/) console.log('All Is OK') }); }) The latest version of MongoDB, driver version 3.0.3