Add a document to MongoDB and then tailor the data using a separate query before insertion

My request is quite simple:

I need to add a new document to my MongoDB database. However, before doing so, I must first check if the slug already exists in the database. If it does, I need to rename the slug before proceeding with the insertion.

I have been attempting to utilize an async await call to verify the existence of the slug and then insert the document accordingly.

mongoClient.connect(function (err, mongoClient) {
    let db = mongoClient.db("articles");

    let categoryCheck = async (db, category_info) => {
        let slugCheck = await db.collection('categories').find({slug: category_info.slug});

        slugCheck.count((err, count) => {
            if (count > 0) {
                let newSlug = `${category_info.slug}_${new Date().getTime()}`;
                console.log(newSlug);
                return newSlug;
            }
            else
                return category_info.slug;
        })
    };

    let categoryPromise = categoryCheck(db, category_info);

    categoryPromise.then(value => {
        console.log(value);
        category_info.slug = value;
    });

    db.collection('categories')
        .insertOne(category_info, (err, data) => {
            assert.equal(null, err);
            res.status(200);
            res.json('success');
        });

    mongoClient.close();
});

The console displays an undefined value from the Promise. Could you please assist me in resolving this issue?

I am still learning the ropes of MongoDB. Is there a more efficient way to handle these two queries together in a single query?

Thank you!

Answer №1

  • Instead of awaiting find(), you should await the command that comes after, such as count(), which actually executes the query.

  • I notice that category_info is missing in the code provided. Assuming it is properly set elsewhere in your code.

  • Remember to return something from your async function, preferably a promise. Currently, you are only returning from the count callback.

With async/await, you can do the following:

const count = await slug_information.count();
if (count > 0) {
    let new_slug = `${category_info.slug}_${new Date().getTime()}`;
    console.log(new_slug);
    return new_slug;
} else {
    return category_info.slug;
}

If you use a callback like (err, count)=>{..}, then you indicate that you will not be using promises, and no promise will be returned for you to wait on.

  • Regarding category_promise.then(..., this part is asynchronous. You cannot be certain that it will resolve before you initiate the insertOne( query. It's highly likely that it has not resolved yet.

Therefore, you can either chain another then block:

category_promise.then(value => {
    console.log(value);
    return category_info.slug = value;
}).then( ()=>{ 
    db.collection('categories')
        .insertOne( ...
});

or make the whole process async:

const MongoClient = require("mongodb").MongoClient;
const category_info = { slug: "abc" };

async function run(req, res, next) {
  const mongoClient = await MongoClient.connect("mongodb://localhost:27017");
  let db = mongoClient.db("categories");

  // With async/await, this part is less necessary but included for completeness.
  let category_information = async (db, category_info) => {
    const count = await db.collection("articles")
      .find({ slug: category_info.slug })
      .count();

    if (count > 0) {
      let new_slug = `${category_info.slug}_${new Date().getTime()}`;
      console.log(new_slug);
      return new_slug;
    } else {
      return category_info.slug;
    }
  };

  category_info.slug = await category_information(db, category_info);
  // Note that insertOne() does not return the inserted document.
  let data = await db.collection("categories").insertOne(category_info);

  res.status(200).json(data);

  mongoClient.close();
}

run(); // or app.get("/some-route", run);

This code is functional, but I haven't tested every case (such as count), so take it with a grain of salt.

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

Retain the contents of the shopping cart even when the page is refreshed

For a course project, I am recreating a grocery store website and need assistance on how to retain the shopping cart values even after refreshing the webpage. Please inform me if more information is required... <button type="button" id= ...

MongoDB: Using the $project operator to filter a sub-array

Let's consider an items (mongoose) schema presented in the simplified format below: { brand: { name: String, }, title: String, description: [{ lang: String, text: String }], shortDescription: [{ lang: String, text: String ...

Move a Java application from a trial SAP HCP to a complete SAP HCP membership

After successfully creating a Java IoT App with Raspberry Pi running on SAP HANA HCP trial account, I am now looking to enhance its functionality within the SAP HANA Development Workbench. Is there a way to import it into the SAP HANA account with ease, o ...

What is the best way to apply a jQuery function to multiple div elements simultaneously?

I am looking to implement a show/hide feature for a <div> using JavaScript and DOM properties. The idea is to use JavaScript's onclick() function with two buttons, show and hide, each in their respective <div>. Here is how it would ideall ...

Need to capture click events on an HTML element? Here's how!

I am attempting to capture click events on an <object/> element that is embedding a Flash file This is the approach I have taken so far: <div class="myban" data-go="http://google.com"> <object class="myban" data="index.swf>">< ...

Tips for dynamically resizing a div element as a user scrolls, allowing it to expand and contract based on

I was working on a project and everything seemed easy until I hit a roadblock. What I am trying to achieve is expanding a div to 100% when scrolling down to the bottom of the div, then shrink it back to 90% at the bottom and do the reverse when scrolling ...

Incorporating multiple colors into a div with jQuery: A guide

I am looking for a way to create a legend by merging a specified number of colors within a div. I came across this useful Sample code that I have referenced. $.each(Array(50), function() { $("<div>").appendTo(document.body); }); var divs = $(&a ...

Enhancing event listener using AngularJS and Jasmine: spying on callback functions

Can someone assist me with spyOnning a method connected to an event using scope.$on in a factory service, using Jasmine? The actual method is being called instead of the spy. Here is a plinkr I created showcasing the issue: http://plnkr.co/edit/2RPwrw?p=pr ...

Create a spectrum of vibrant colors depending on the numerical value

I'm attempting to create a function that generates rainbow colors based on a numerical value. var max = 10000; var min = 0; var val = 8890; function getColor(min, max, val) { // code to return color between red and black } Possible Colors: Re ...

Having trouble retrieving the necessary data to generate a menu, the getStaticProps function is coming back as undefined

I'm currently working with Next.js 13 & Strapi, and my goal is to create a Menu component utilizing the getStaticProps function. To achieve this, I've implemented a Layout component within the _app.js file, and nested a Menu component inside the ...

Utilize Javascript to create a function that organizes numbers in ascending order

Is there a way to modify this code so that the flip clock digits appear in ascending order rather than randomly? $( '.count' ).flip( Math.floor( Math.random() * 10 ) ); setInterval(function(){ $( '.count' ).flip( Math.floor( Math.rand ...

How can you switch the property of an object in VueJS?

I am currently working with an array called cars, which contains names of cars as well as a property called starred. My goal is to toggle the value of starred between true and false for each car, ensuring that only one car can have starred set to true at a ...

Discover how to access the rotation of an object within ThreeJS based on

Currently in my code, I have implemented rotation restrictions around a specific axis using the following snippet: if (obj.rotation.x > -0.5) { // execute rotation } Initially, this setup worked perfectly. However, things took a turn when I introd ...

Enhancing collaboration: Seamlessly sharing interface/interface/model files in the integration of

Currently, I am engrossed in developing an application with an Express backend and Typescript whilst utilizing Angular for the frontend. The only snag I'm facing is that I require interface/models files from the backend to be accessible on the fronten ...

Is there a bug in Firefox concerning the accuracy of document.body.getBoundingClientRect().top?

When I access Firefox version 17.0.1 and request document.body.getBoundingClientRect().top; on a simple site with no CSS styling applied, it returns an incorrect value. Instead of the expected 8, which is the default for the browser, it shows 21.4. However ...

Refresh the page without reloading to update the value of a dynamically created object

Maybe this question seems silly (but remember, there are no stupid questions).. but here it goes. Let me explain what I'm working on: 1) The user logs into a page and the first thing that happens is that a list of objects from a MySQL database is fet ...

Troubleshooting the encryption of XSSFWorkbook in styles.xml during the save process with Apache POI v3.16

Currently, I am using Apache POI 3.16 with Java version 1.7.0-251 (Unix). I found inspiration in an example provided by @Aniruddh Chandegra on how to create and edit a password-protected excel sheet using Apache POI 3.14 (Link here). [EDIT - Below is the ...

Best practices for implementing the map function with TypeScript

I'm currently working on mapping types in a DB using the Map function in JavaScript. This is my first time trying to do this, and I'm eager to learn but I've hit a roadblock. Here is the structure of the DB: const db = { data: [ { ...

Tips for setting up a bookmark in bootstrapvue

Hello everyone, I am currently working with bootstrapvue and I need help figuring out how to add a favorite icon. The documentation only provides icons for rating systems. I have a list of reports and I want users to be able to mark their favorites, simil ...

The program encountered an error while trying to access the undefined property '_header'

An issue arises when the app.use(express.static("web")) line is executed. var express = require('express')(); var app = express(); var http = require('http').Server(app); var io = require('socket.io')(http); //app.get(&apo ...