Tips for adding one document to two separate collections using JavaScript and MongoJS

Having trouble inserting data into two separate tables using javascript and mongojs. While I was able to successfully insert into a single collection by following the npm mongojs documentation, I couldn't find a solution for multiple collections on this platform. Any assistance would be greatly appreciated.

// var Delivered = require('../model/booking/booking').Delivered,
var Completed = require('../model/booking/booking').Completed,
express = require('express')
    app = express(),
    mongojs = require('mongojs'),
    db = mongojs('mongodb:coolection',["completeds", "delivereds","deliveredhistory"]);

function route(app){
    app.post('/shipper/completed',function(req, res){

    var item_id = req.body.item_id
        var id = mongojs.ObjectId(item_id);

        db.delivereds.findAndModify({
            "query":{ "_id": id },
            "remove": false
            },

            function(err,data) {

                    if (data) {

                        db.completeds.insert(data,function(err,data){
                            if(err){
                                res.json({
                                    status:400,
                                    message:"Failed to mark as complete",
                                    err:err
                                })
                            }
                            else{
                                res.json({
                                    status:200,
                                    message:"Job successfully completed",
                                    data:data

                                });
                            }
                        });

                        // Inserting into another collection 'deliveredhistory'
                        db.deliveredhistory.insert(data,function(err,data){
                            if(err){
                                console.log("Insertion into deliveredhistory failed");
                            }
                            else{
                                console.log("Data inserted into deliveredhistory successfully");
                            }
                        });
                    } 
                    else {
                        console.log("fake number")
                        res.json({
                            status: 403,
                            message:'This load is not available for accepting'
                         })
                   }

               })
        })
    }
module.exports.route = route;

I'm still struggling with inserting data into another collection called 'deliveredhistory'. Can someone please provide guidance?

I attempted the following code snippet but it didn't work:

(db.completeds&&db.deliveredhistory)insert(data,function(err,data){

Answer №1

After some troubleshooting, I managed to find a solution.

I devised a new approach for handling deliveredhistory by triggering the insert method after the completion of if(err){....} without any errors. Then, I incorporated another insert method before res.json({...}) within the else condition.

This is how it looked:

if (data) {

                    db.completeds.insert(data,function(err,data){
                        if(err){
                            res.json({
                                status:400,
                                message:"Failed to mark as complete",
                                err:err
                            })
                        }
                        else{
                           db.deliveredhistory.insert(data) //this is where the insert for the second collection took place
                           res.json({
                                status:200,
                                message:"Job successfully completed",
                                data:data

I trust this explanation can benefit someone facing a similar issue.

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

Can you explain the variance between calling mongoose.Schema() and creating a new instance with new mongoose.Schema()?

Can you explain the distinction between mongoose.Schema() and new mongoose.Schema() methods? I have tried both approaches, and it seems like they yield similar results. Are there any notable differences or implications to consider? ...

Establish a production-ready integration between MongoDB and Meteor

For the purpose of a demo, I have successfully deployed my meteor application on localhost by following the method described here. $export MONGO_URL='mongodb://localhost' $ export PORT=3000 $ export ROOT_URL='http://example.com' $ nod ...

using async/await to retrieve data from a Google spreadsheet in Node.js

How can I use a for-loop to iterate through sheets in a Google spreadsheet and access specific cells within each sheet? I have a Google spreadsheet with Sheet1, Sheet2,... , Sheet5 where the cell values are Value1,..., Value5. The expected result should be ...

What steps can be taken once the browser has completed all rendering processes?

I have a large form that functions on older PCs. This form is a component of a thin client system and is implemented using AngularJS to create a Single Page Application. One of the tabs on the SPA includes this form. Upon opening the form, requests are se ...

Save user entries in a database array

I'm working on developing a platform for advertisements where users can create detailed profiles with images. To achieve this, I need to store the information in an array within a backend database for future retrieval. Below is an example of the backe ...

What is the most effective method for sharing a form across various components in Angular 5?

I have a primary form within a service named "MainService" (the actual form is much lengthier). Here is an overview- export class MainService { this.mainForm = this.formBuilder.group({ A: ['', Validators.required], B: & ...

Encountering a NULL argument in an MVC controller when executing an Ajax post request

I am facing an issue with my ajax post request where I send JSON string data, but it is showing null in my controller. Here is the AJAX Call: var jsonData = JSON.stringify(matrixPresenter); $.post("/matrix/Savematrix?matrixData=" + jsonData , fu ...

Exploring the integration of query parameters in Postman using mongoose

In my code, I have a driver.js file that holds a driver schema, and a driverController.js file with REST methods including GET, POST, DELETE, and PUT. What I want to achieve is to send a GET request to http://localhost:3000/drivers?available=true This re ...

Tips for reducing image file size using ImageMinimizerWebpackPlugin in Next.js (webpack 5)

When attempting to use this plugin for image compression, I am encountering an issue where the build process completes successfully, but the images remain uncompressed. As a beginner with webpack, I'm unsure of what might be causing this problem. Cou ...

Setting up the MEAN (Mongo, Express, Angular, Node) stack on Nitrous.IO: A Comprehensive Guide

This weekend, I am planning to tackle two items on my 2013 project list: Experiment with Cloud Development Learn about ANGULAR.JS My plan is to set up the MEAN stack using Nitrous.IO and then use it to complete an Angularjs tutorial project. Questions: ...

Incorporate JavaScript to include a new class and attribute

Apologies for any language barriers.. I grasp that it involves using addClass and removeClass, but I am uncertain about how to write the terms. I need to ensure that if the screen resolution is less than 768 pixels, then the attributes id="dLabel" type="b ...

Identifying the presence of node.js on your system

After installing node.js, I found myself at a loss on how to run applications. Despite the lack of instructions, I was determined to test if it was working by executing a script named hello.js: console.log('hello world'); I couldn't help b ...

Is there a way for me to showcase information?

I am currently facing an issue with displaying user information retrieved from my database using AngularJS. The code snippet below shows how I am trying to get the user data: angular.module('listController',[]) .controller('listCtrl' ...

Show or hide a specific element based on whether a certain radio button is selected or deselected

After successfully displaying an element on radio button selection, I encountered the issue of the selected element remaining visible when another radio button in the group is chosen. What aspect am I overlooking? Regarding hiding elements with vanilla Ja ...

I am looking to utilize the data from a POST request to dynamically update the DOM through a script.js file. How can

After sending a post request, I am looking to update my database and then use an array to dynamically update the HTML content. However, I am struggling with how to pass this data to my script.js file. Here is my progress so far: SERVER let expenseAmo ...

receiving an undefined value from a remote JSON object in Node.js

I have been struggling to extract the specific contents of a JSON api without success. Despite my best efforts, the console always returns undefined. My goal is to retrieve and display only the Question object from the JSON data. After spending several h ...

What is the URL I need to visit in my browser to monitor updates while running npm?

I am interested in utilizing npm to monitor any changes made in my project and immediately view them in my browser. Essentially, I have been implementing npm using this modified code snippet from this source, which allows me to run the command npm run buil ...

Exploring the contrast between Vuex store WATCH and SUBSCRIBE

Can you explain the main distinction between watch and subscribe, and when it is most appropriate to use one over the other? According to information on the Vuex official documentation, both methods appear to be essentially identical in functionality and p ...

What is the most effective method for invoking an inherited method (via 'props') in ReactJS?

From my understanding, there are two primary methods for calling an inherited method on ReactJS, but I am unsure which one to use or what the best practice is. class ParentCont extends React.Component { constructor(props) { super(props); t ...

Tips for securely transmitting data via a hidden form using the POST method

I have a query that displays records of people, and I want to send the id_Persona using a hidden form through a post function to the idsPersonas.php page. However, when I try to do this, it redirects me to an undefined page. Here is the code snippet: < ...