Discover the step-by-step process for moving data between collections in MongoDB

I am currently working on nestjs and have two collections, one for orders and the other for payments. My goal is to retrieve a single entry from the orders collection and save that same entry into the payments collection.

Below is the code for the services:

async order(name){
    const list = this.usersmodel.find({name: name}).exec()
    //return list
    try {
        if(list) {
            const x = this.usersmodel.aggregate([
                { $out: "payment" }
            ])
            return "data saved in payment collection"
        }
    }
    catch(error) {
        return(error.message)
    }
}

Below is the code for the controller:

@Get('orderdata')
async orderdata(@Body('name') name) {
    return this.usersService.order(name)
}

Despite using this code, I did not achieve the desired output nor did I encounter any errors. When testing the API in Postman, I received the message "data saved in payment collection" but the entries were not actually being saved in my payment collection.

Answer №1

I believe the issue lies within this particular line of code

const list = this.usersmodel.find({ name: name }).exec()

This section of code is asynchronous, meaning that the subsequent lines will be executed without waiting for the resolution of the 'list' variable

You must use the await keyword to ensure that JavaScript waits for this line to finish executing before moving on to the next lines

const list = await this.usersmodel.find({ name: name }).exec()

Furthermore, the aggregate pipeline is transferring all order documents to the payment collection without any filtering in place

Therefore, you need to include a $match stage in your aggregate pipeline to filter the list of orders based on the specified name

It's important to note that the await keyword is required in the aggregate process as well since it is also asynchronous, ensuring that the return statement is only executed after the aggregation is complete

Therefore, the entire function should resemble something like this

async order(name) {
    const list = await this.usersmodel.find({ name: name }).exec()
    //return list
    try {
        if(list){
            await this.usersmodel.aggregate([ // await is necessary here
                { $match: { name: name } }, // filtering the orders
                { $out: "payment" } // transferring them to the payment collection
            ])

            return "Data has been saved in the payment collection"
        }
    }
    catch (error) {
        return(error.message)
    }
}

I hope this explanation proves helpful

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

Transform a base64 image into a blob format for transmission to the backend via a form

Is there a way to convert a base64 string image to a blob image in order to send it to the backend using a form? I've tried some solutions like this one, but they didn't work for me. function b64toBlob(b64Data, contentType='', sliceSiz ...

Flow error: Unable to access the value of this.props.width as the property width is not defined in T

In my React Native project, I am utilizing Flow for type checking. For more information, visit: I currently have two files named SvgRenderer.js and Cartoon.js where: Cartoon extends SvgRenderer Below is the source code for both of these files: SvgRend ...

Encountering a tuple type TypeScript error with a spread argument is far too frequent an occurrence

Encountering this error is becoming a frequent occurrence for me, and I am currently unable to resolve it. src/graphics.ts:105:55 - error TS2556: A spread argument must either have a tuple type or be passed to a rest parameter. 105 _queue.forEach((_ ...

Storing Many-to-One Relationships in Mongoose from Both Ends

I have recently started working with MongoDB and using Mongoose for my project. In my database, I have two models: users and recipes. User Model: recipes: [{ type: Schema.Types.ObjectId, ref: 'recipes' }], Recipe Model: _creator: { ...

Setting up Emotion js in a React TypeScript project using Vite 4

Currently, I am in the process of transitioning from Webpack to Vite for my React Typescript application. I have been attempting to integrate Emotion js into the project. "@vitejs/plugin-react": "^4.0.1", "vite": "^4.3.9 ...

Combining Two Models in Sails.js

I'm facing an issue with linking two models in sails. I have two models: 'Singer' and 'Country'. In the 'Singer' model, I have an attribute 'singer_country' which represents the id of the 'Country' mod ...

Enhancing the type safety of TypeScript Generics

Uncertainty looms over me - am I committing an error, or is this all part of the plan... Within my academic domain class Collection<E> { ... } Lies a function public Insert(item: E): void { ... } I construct a specific instance of my list const ...

Steps to verify the existence of an email address without including the current record in Mongoose

Recently, I've set up an update route for a product where certain fields need to be unique. During the creation of a product, I'm currently checking for uniqueness like this: const emailExists = await Foodlancer.findOne({ email: values.email }); ...

Access the file stored in GridFS and convert it to a standard IO::File object for further

Currently, I am utilizing GridFs to store various files including Excel files. My goal is to leverage the Spreadsheet gem for parsing these Excel files. I attempted the following code snippet with no success: 1.9.3p194 :036 > db = Mongo::Connection.ne ...

Encountering an issue with Angular 12 where a TypeError is being thrown, specifically stating "Cannot read properties of null (reading 'length') at

I encountered an error message while making a http request in my Angular Service. Strangely, this error only occurs after I logout, but it disappears upon logging back in: Below is the code snippet of my authentication Service: import { Injectable } from ...

Maximize the performance of displaying images

At the moment, I have a set of 6 graphics (0,1,2,3,4,5)... The arrangement of these graphics looks fantastic! However, I am facing an issue when a user only has 3 graphics, for example 0, 2, and 5. In this scenario, my graphics do not line up correctly. D ...

Error: The server is unable to process the POST request to /api

Currently following a tutorial on YouTube: https://www.youtube.com/watch?v=4ECVE6TXKLQ&list=PLI-gk4ISRzCPlJjCz3yuAhL8vnmK6KWr7&index=11 After setting up a server listening on port 8080 and connecting to MongoDB Atlas successfully, the next step ...

Accessing the 'comment' property within the .then() function is not possible if it is undefined

Why does obj[i] become undefined inside the .then() function? obj = [{'id': 1, 'name': 'john', 'age': '22', 'group': 'grA'}, {'id': 2, 'name': 'mike', &apo ...

Tips for adding a time increment of 24 hours to a date variable in Angular 6

My goal is to update a date variable called EndDate stored in localStorage by adding exactly 24 hours to it. The current value in the localStorage is Sun Jun 09 2019 20:39:44 GMT+0530 (India Standard Time). var endDate = new Date(); endDate.setDat ...

Issue with Angular 6 auth guard causing logged-in users to remain on a blank page

I came across this answer and am tweaking it to work with my authentication system: Angular 6 AuthGuard However, I'm facing an issue where after successful authentication, instead of redirecting to the specified URL, the auth guard leads to a blank p ...

The mongoose schema fails to recognize certain values

Feeling frustrated. I defined a Schema like this: var UserSchema = new Schema({ userNick : { type: String, required: true, index: { unique: true, sparse: true } } , userEmail : { type: String, required: true, index: { unique: true, sparse: ...

How can you merge arrays in Angular based on their unique names?

Is there a way to combine objects within the same array in Angular based on their names? [{ "name":"Navin", "id":"1" }, { "name":"Navin", "mark1":"98" ...

Is there a circular dependency issue with ManyToMany relationships in Typescript TypeORM?

Below are the entities I have defined. The Student entity can subscribe to multiple Teachers, and vice versa - a Teacher can have many Students. import { PrimaryGeneratedColumn, Column, BeforeInsert, BeforeUpdate } from "typeorm" /* * Adhering to ...

The Graphql mutation successfully updated the user data, however, it mistakenly changed the password resulting in me being unable to log in after

I am relatively new to this so please bear with me. Every time I execute the mutation, I can see the changes in mlab and the user gets updated successfully. However, when I log out and try to log back in, I encounter difficulties. My suspicion is that the ...

How can I verify the presence of email and mobile numbers in my MongoDB database?

const express = require('express'); const router = express.Router(); require('../db/conn'); const User = require('../model/userSchema'); router.get('/', (req, res) => { res.send(`Hello World from the server ...