Stuck again node express and mongo problem

I’m trying to pass data from my server app.js to my database file

Relevant server code app.js

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

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

Relevant database code


var userDataFinal = function getUserName(user){
    return user;
}

var exports = module.exports = {getUserName};

console.log(userDataFinal)

This gives me a reference error: getUserName is not defined,

however if I keep the console.log() within the scope of the getUserName function the code runs fine. I need to be able to access the data in user outside the scope of the getUserData function and it doesnt seem to be working

You will need to export userDataFinal instead of getUserName

Also, remove the var exports = ?

It could be assigning module.exports to exports instead of exporting it.

The associativity of the assignment operator is right associative so that line is parsed as var exports = (module.exports = {getUserName});

The problem is exporting the right thing as you pointed out :slight_smile:

I made the changes however I’m getting an unhandled promise rejection warning now



var userDataFinal = function getUserName(user){
    return 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...')
});

I can’t remember, doesn’t insertOne return a promise? if so then it could be that the call to insertOne has rejected and you haven’t caught it

that database is also trying to create a new document the moment it start up, It’s not waiting until the form is submitted

hold on ill check the docs

just for completion, this is an exercise just to help me learn

. Heres a better representation of what it is I’m trying to achieve

There’s a lot going on in your function here that ought to be changed…

You might find it helpful to read up on promises first: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

Did you really mean to pass a function in to insertOne? that seems wrong to me but I’d have to check the docs again

You’re also adding the document in the callback to connect, so of course it doesn’t wait for anything

1 Like