Submit a single data value to two separate models in JSON format using MongoDB

I recently developed a code with 2 essential functions:

module.exports.registerAccount = (reqBody) => {

let newAccount = new User({
    firstName : reqBody.firstName,
    lastName : reqBody.lastName,
    email : reqBody.email,
    mobileNum : reqBody.mobileNum,
    password : bcrypt.hashSync(reqBody.password, 10)
})

return await newAccount.save().then((account, error) =>{
    if(error){
        return false;
    }
    else{
        return true;
    }
})

let newCustomer = new Order ({
    FirstName : reqBody.firstName,
    LastName : reqBody.lastName,
    MobileNum : reqBody.mobileNum
})

return await newCustomer.save().then((customer, error) =>{
    if(error){
        return false;
    }
    else{
        return true;
    }
})
}

The purpose of newAccount is to handle the user model while newCustomer is responsible for the order model. After running some tests, I encountered no errors with the codes, but unfortunately, newCustomer isn't being saved in its designated model as expected. I even attempted switching the positions of the two models, which resulted in the same outcome switch. Is there any effective method to ensure that both operations work flawlessly together? Any suggestions or tips would be greatly appreciated.

Answer №1

Discovering the resolution;

saveNewAccount = newAccount.save();
saveNewCustomer = newCustomer.save();

return saveNewAccount && saveNewCustomer.then((account, error) => {
    if(error){
        return false;
    } else {
        return true;
    }
})

Utilizing && between newAccount and newCustomer due to only one return statement being functional.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Checking connectivity in an Ionic application

Within my Ionic application, I am faced with the task of executing specific actions depending on whether the user is currently connected to the internet or not. I plan on utilizing the $cordovaNetwork plugin to determine the connectivity status within the ...

Discovering the file extension and ensuring its validity when imported from Google Drive

I am facing an issue with a select tag that has 3 options: powerpoint, pdf, and spreadsheet. When uploading from Google Drive, there is no validation in place, so I can give a ppt link to the pdf option and it will still upload. Can someone help me with va ...

Increasing the margin-left automatically in Bootstrap 3.0.0

I am looking to automatically generate margin-left in the ".card" class "style" element every time a post is entered on a page. My jQuery version is 1.12.4 This is my idea: If the .card CSS style has a margin-left of 0 and width of 479px, set position to ...

Unveiling the information retrieved from an AJAX request during page load

I've been working on a unique concept for my website. Instead of displaying data from a JSON file upon load, I want it to render only when a specific click event occurs. Initially, I tried using callbacks but soon realized the flaws in that approach. ...

Set my click event handler back to its default setting

I'm struggling with resetting a click function after it completes. How can I make sure it's ready to run again? $('body').on('click', '#ConfirmBet', function () { function randomImg() { var imgs = $(&apo ...

The page could not be generated due to a server error with the syntax. More specifically, an Unexpected token 'export' caused a SyntaxError

Encountering an issue while attempting to retrieve data using getServerSideProps. Seeking assistance, thank you! Server Error SyntaxError: Unexpected token 'export' This error occurred during the page generation. Any console logs will be shown ...

Having trouble with submitting data in an ExpressJS POST request while using mongoose?

As I embark on building my first express.js application, I encounter my initial obstacle. The setup is rather simple. Routes in app.js: app.get('/', routes.index); app.get('/users', user.list); app.get('/products', product. ...

How can I use $ne in MongoDB to determine if a field does not contain any value from a given array?

Is there a method to query a field that does not include any elements from an array? For instance, suppose I have an array of objects (venue): db.collection.aggregate([{ $match: { roomNo: {$ne: venue}}}, ]) How can I access the arra ...

Tips for Incorporating xmlhttp.responseText in If Statements

This is the code snippet from my save_custLog_data.php file: <?php $a = $_GET['custEmail']; $b = $_GET['pswrd']; $file = '/home/students/accounts/s2090031/hit3324/www/data/customer.xml'; if(file_exists($fi ...

Scroll horizontally on a webpage using drag with JavaScript

I have been working on a unique horizontal website design that allows users to scroll horizontally by dragging the screen. I managed to successfully implement the horizontal scrolling feature, but I am facing difficulties in adding the horizontal drag-to-s ...

When implementing ReplaySubject in Angular for a PUT request, the issue of data loss arises

I seem to be encountering a problem with the ReplaySubject. I can't quite pinpoint what I've done wrong, but the issue is that whenever I make a change and save it in the backend, the ReplaySubject fetches new data but fails to display it on the ...

Having issues with handling ajax response in a Node.js application?

I am encountering an issue with my ajax post request to my node js backend. After sending the request and receiving a response, instead of updating just the resulttoken in the view, the entire HTML page seems to be loaded according to the console. I am see ...

Adjusting the position of a stationary element when the page is unresponsive and scrolling

Managing a large web page with extensive JavaScript functionality can be challenging, especially when dealing with fixed position elements that update based on user scroll behavior. A common issue that arises is the noticeable jumping of these elements whe ...

How can I efficiently update child states within a parent class using ReactJS?

Exploring the parent component class Root extends React.Component { constructor(props) { super(props); this.state = { word: Words, }; } c ...

Forwarding information and transferring data from a Node server to ReactUIApplicationDelegate

I am currently working on a NodeJS server using Express and React on the front-end. I am trying to figure out how to send data from the server to the front-end without initiating a call directly from the front-end. The usual solutions involve a request fro ...

Dynamically binding image URLs in VUEJS

Below is the JSON data containing button names and their corresponding image URLs: buttonDetails= [ { "name": "button1", "images": [{ "url": "https://localhost:8080/asset/d304904a-1bbd-11e6-90b9-55ea1f18bb ...

A step-by-step guide on retrieving information from Material UI components and incorporating an onSubmit feature to transmit data to the backend server

I've recently started working with react/material-UI. While working on a project, I turned to youtube videos and various resources for guidance. I opted for material-UI due to its user-friendly nature. However, I'm currently facing a challenge ...

Is it possible to utilize Ajax submit requests within a (function($){...}(jQuery)); block?

As a PHP developer with some knowledge of JavaScript, I am currently using AJAX to send requests to the server. I recently came across the practice of enclosing all code within an anonymous JavaScript function like: (function($){ //code here }(jQuery)). Fo ...

The submit button remains unresponsive, yet upon removing its JavaScript code, it functions smoothly

This is the content of my index.html file. It contains JavaScript code. However, there seems to be a problem with the JavaScript validation as the Submit button does not perform any action when clicked. Surprisingly, when I remove the JavaScript code, the ...

Is the concept of LinkedList index applicable in the field of Data Structures and Algorithms (DSA)?

Is there an index feature in LinkedList that allows for accessing elements like in arrays? If so, can you explain how the indexing works within the LinkedList concept? Thank you I am new to LinkedList and would like to grasp the fundamental concept behin ...