A
A
Alexey Yakovlev2020-02-27 14:33:54
JavaScript
Alexey Yakovlev, 2020-02-27 14:33:54

Error when clicking on the register button, what should I do?

I start the server, go to the sign up page, click register and get an error - TypeError: db.collection is not a function
server:

'use strict';

let bodyParser = require('body-parser');
let express = require('express');
let MongoClient = require('mongodb').MongoClient;
let ObjectID = require('mongodb').ObjectID;

let app = express();
let db;

let parser = bodyParser.urlencoded({ extended: false });
app.use('/public', express.static('public'));
app.set('view engine', 'ejs');

// Регистрация
app.get('/sign-up', function(req, res) {
    res.render('signup');
});
// Получение данных 
app.post('/sign-up', parser, function(req, res) {
    let user = {
        name: req.body.name
    }
    res.render('exit', {data: req.body});

    // Обращение к коллекции users
    db.collection('users').insert(user, function(err, result) {
        if (err) {
            console.log(err);
            return res.sendStatus(500);
        }
        res.send(user);
    });
});
// Профиль
app.get('/profile', function(req, res) {
    res.render('profile');
    db.collection('users').find().toArray(function(err, docs) {
        if (err) {
            console.log(err);
            return res.sendStatus(500);
        }
        res.send(docs);
    });
});
// Нахождение пользователей через id
app.get('/profile/:id', function(req, res) {
    db.collection('users').findOne({ _id: ObjectID(req.params.id) }, function(err, doc) {
        if (err) {
            console.log(err);
            return res.sendStatus(500);
        }
        res.send(doc);
    });
});
// Запуск сервера
MongoClient.connect('mongodb://localhost:27017/alldatabase', function(err, database) {
    useUnifiedTopology: true;
    useNewUrlParser: true;

    if (err) {
        return console.log(err);
    }
    // Ссылка на бд
    db = database;
    app.listen(3000, function() {
        console.log('Подключение');
    });
});

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander Cheremkhin, 2020-02-27
@aleshaykovlev

https://mongodb.github.io/node-mongodb-native/api-...
format connect(url[, options], callback)
Apparently a bug in MongoClient.connect

// Запуск сервера
MongoClient.connect('mongodb://localhost:27017/alldatabase', function(err, database) {
    useUnifiedTopology: true;  //  <---????
    useNewUrlParser: true;  //  <---???? неправильно опции установлены

   ...

Right below
// Запуск сервера
MongoClient.connect(
  'mongodb://localhost:27017/alldatabase',  // строка подключения
  {
     useUnifiedTopology: true,  // установка опций
     useNewUrlParser: true
  },
  function(err, database) {  // callback
    if (err) {
        return console.log(err);
    }
    // Ссылка на бд
    db = database;
    app.listen(3000, function() {
        console.log('Подключение');
    });
});

E
emp1re, 2020-02-28
@emp1re

Because db = undefined.
You need to wait for the callback to be called before registering methods on the empty Object.
The initialization of the database must take place before the registration of the router.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question