1

I’m trying to pass data from my server app.js to my database file so that I can store it into MongoDB atlas.

I can see where the problem is I'm honestly just not sure how to go about fixing it. The problem seems to be two parts.

1.) I'm passing a function into .insertOne and not an object, this is resulting in a promise error. When I try to change things in the userDataFinal function I start running into scope errors and things not being defined. I'm not really sure how to fix this.

2.) my code is trying to create a new document as soon as it starts up because db.collection('User').insertOne(userDataFinal); is located in the .connect callback function.

I need this code to run only when a put request has been made on the client side.

relevant server code app.js

const base = require('./base.js');

app.post('/',(req, res)=>{
    var userName = req.body;
    base.userDataFinal(userName);
    res.render('index');
});

Relevant database code base.js

var userDataFinal = function getUserName(user){
    console.log(user);
}

module.exports = {userDataFinal};



////////////////////////////////////////////////////////////////////////


    // connects to the database
MongoClient.connect(URL, {useNewUrlParser: true}, (error, client)=>{
    if(error){
        return console.log('Could not connect to the database');
    }

    // creates a new collection 
    const db = client.db(database);

    // adds a document to the designated collection
    db.collection('User').insertOne(userDataFinal);


console.log('Database is connected...')
});

Heyrio
  • 129
  • 2
  • 11

1 Answers1

1

First, you are passing a callback into your MongoClient.connect() function. This callback is useful when you want to make sure that you are connected.

As you said it, you want your code to run only when the request has been made. You can remove your insertion from the connect, but you can still keep the error handling part as it is always useful to know why there was a db connection error.

Also, you are calling the mongo insertOne method, that expects an object. You are passing it a function.

EDIT: Create a db variable outside all your functions, then assign it from the Mongo connect callback once you have access to the client. You will be able to use this db later in the routes.

var MongoClient = require('mongodb').MongoClient;

var db; // Will be set once connected

MongoClient.connect(URL, {useNewUrlParser: true}, (error, client)=>{
    if(error){
        return console.log('Could not connect to the database');
    }
    db = client.db(database);
    console.log('Database is connected...')
});

app.post('/',(req, res)=>{
    var userName = req.body.username;
    db.collection('User').insertOne({ username: userName });
    res.render('index');
});

Please note that you are probably passing the userName through the body, in this case you need to retrieve it that way: req.body.username (if you named the related body parameter username).

Scaraux
  • 3,841
  • 4
  • 40
  • 80
  • Thank you for the clear explanation, I never even though of adding the document directly in one of the servers routes. However there's still a problem because in ``` app.post('/',(req, res)=>{ var userName = req.body.username; db.collection('User').insertOne({ username: userName }); res.render('index'); }); ``` db is not defined in that block – Heyrio Apr 16 '19 at 22:49
  • You need to better understand how to structure JavaScript code, more precisely for node.js applications using exports/require or export/import for newest versions. From my undestanding you are using the MongoDB client in your Node.js application. Either you import it in your main file (see my edited answer), or you define the logic in a different file as you were doing it before. – Scaraux Apr 16 '19 at 22:54
  • If you wish to use your db connection and share it through different .js files, take a look at: https://stackoverflow.com/questions/24621940/how-to-properly-reuse-connection-to-mongodb-across-nodejs-application-and-module Also might be helpful: https://zellwk.com/blog/crud-express-mongodb/ Finally for your global understanding of modules: https://www.sitepoint.com/understanding-module-exports-exports-node-js/ – Scaraux Apr 16 '19 at 23:02
  • Yeah, up until now all my applications have been a single file front end or backed. Getting everything communicating with multiple parts is where I'm getting stuck and lost. Thank you for your response I'll spend some time reading through it. – Heyrio Apr 16 '19 at 23:06