How to efficiently create a unique object on MongoDB during the first instance

In the project I'm working on, there is a feature where a user can create a safe by visiting /mysafe. However, I want this safe to be created only once when they first visit the page. Subsequent visits should redirect them to /mysafe/theidofit.

Have a look at my app.js:

app.get('/mysafe',async (req,res)=> {
    const safe=new Safe()
    safe.author=req.user._id
    safe.save()
    res.redirect(`/mysafe/${safe._id}`)
})

I attempted to add a middleware for this functionality, but since my user schema does not have a 'safe' property defined, I'm unsure if I need to define it or if there's another way around it.

const UserSchema = new Schema({
    email: {
        type: String,
        required: true,
        unique: true
    }   
});

Answer №1

When a user accesses the '/mysafe' route, the following asynchronous function is executed:
 app.get('/mysafe', async (req,res)=> {
  let safe = await Safe.findOne({author: req.user._id});
  if (!safe) {
    safe = new Safe()
    safe.author=req.user._id
    safe.save()
  }
  res.redirect(`/mysafe/${safe._id}`)
})

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

An error occurred with Express and Passport: ['ERR_HTTP_HEADERS_SENT']

Currently, I am diving into an ebook tutorial and have encountered a roadblock in a particular piece of code. The code is designed to take a username and password in JSON format through Insomnia or Postman, and it should return a login success cookie. Howe ...

Switch up the positioning of elements using jQuery

My webpage contains multiple elements that are absolutely positioned with the CSS attribute "top." I am looking to adjust the top position of each element by 20px. This involves retrieving the current top position and adding 20px to it. The quantity of e ...

Time taken to execute all the tests using the karma runner

We have recently transitioned to running unit tests remotely using browserstack across multiple browsers and operating systems with the help of the karma-browserstack-launcher plugin. The current output of our test run appears as follows: $ grunt unit:re ...

When a user inputs in the field, it automatically loses focus

An error is encountered in two scenarios: When the input includes an onChange event handler When the input is located within a component that is called on another page For instance: In Page1.js, we have: return <div> <Page2 /> </div ...

Utilizing EJS to display dynamic data from a JSON file in a visually appealing D

*Excited about learning express! Currently, I have two files - index.ejs and script.js. The script I've written successfully fetches JSON data from an api. const fetch = require("node-fetch"); const url = '...' fetch (url) .then(resp ...

Deleting the stylesheet exclusively within the confines of the React application window

Here is an image that will help illustrate the issue: https://i.stack.imgur.com/VA7fw.png If you want to check out the code sandbox for this problem, you can visit: https://codesandbox.io/s/annoying-stylesheet-2gpejc?file=/public/index.html I am current ...

The ineffectiveness of setting width to 0

When I set @media screen and (max-width: 700px), aside {width: 0}, it doesn't disappear. Even after resizing the window, it remains as null space with width: 52px. What could be causing this issue and how can I resolve it? * { margin:0; padding ...

Using JQuery and Javascript to retrieve information from one drop down list based on the selection made in another drop down

I'm currently working on a project that involves 2 drop-down menus. The first menu allows you to select a general model, while the second menu displays specific models based on your selection. http://jsfiddle.net/QskM9/ Here's an example of how ...

How can you set a predetermined value for a dropdown menu after populating it with data from a Django database?

I currently have a query in my Views.py file that is used to populate a dropdown menu. The query works properly, but I need it to display a specific value that is stored in a variable based on the user's selection. For example, let's suppose we ...

Avoid displaying "undefined" on HTML page when Firebase database value is empty

I am trying my best to explain my issue, although I struggle with scripts. Please bear with me and help me improve. ˆˆ Below is the script I am working on. The goal is to display all records with a date set for 'today or in the future'. Progr ...

Utilizing Vuetify 2 skeleton-loader to customize loading states through Vuex store manipulation

Utilizing the Vuetify v-skeleton-loader component to wrap a v-data-table component. The server-side pagination and sorting in the data-table component are set up. To enable server-side pagination, the documentation recommends monitoring the options objec ...

Attempting to extract a user handle from the URL structure within an Express application

I'm currently working on developing a Minecraft API that can retrieve data from a database. I am aiming to create something akin to Mojang's API structure. /session/minecraft/profile/{uuid} My goal is to utilize Express in such a way that, based ...

An express.js mishap occurred when attempting to process an HTTP POST request using an AJAX client-side, resulting in a

Encountering a 500 Internal Server Error when attempting to send an HTTP POST request from client-side JavaScript using JQuery AJAX in Express.js. The code resides in the p.js file on the client. function dataHandler(conn,data) { var datalol=data; ...

Tips for saving a picture within a mongodb record using python and pillow

Currently, I am working on a piece of code that generates a thumbnail image from a specified URL: r = requests.get(image_url, stream=True, headers=headers) size = 500, 500 img = Image.open(r.raw) thumb = ImageOps.fit(img, size, Image.ANTIALIAS) My goal i ...

The Foolish Mistake: Undetermined Dollar Sign

Can someone please help me with this issue? I've searched everywhere but I can't seem to fix the "Uncaught ReferenceError: $ is not defined" error. I have rearranged my script, tried putting it at the bottom, but nothing seems to work. Any sugges ...

Using JavaScript with Selenium, you can easily clear the input field and send

Here is a question input field. When clicked on, the h3 element with the name will disappear and the input tag will appear for entry of a new name. <td style="width:92%;"> <h3 id="question_tex ...

React-beautiful-dnd does not function properly when used with the overflow auto property

Currently, I'm in the process of developing an application similar to "Trello" and have encountered a few challenges along the way. I've successfully created the main components such as the "Board," "Cards," and "Tasks." Each card has a fixed wid ...

The NodeJS/Express error message "Router.use() requires a middleware function but got an Object" is thrown when using app.use("/parse")

I'm currently following the installation guidelines for parse-server, specifically attempting to install it using NodeJS and Express. As outlined in the instructions, here is the code I have to set up the server: var express = require('express&a ...

Passing props from a Higher Order Component (HOC) to child components in next.js using get

I am looking to implement an HOC (Higher Order Component) for pages within my application that can provide some information stored in local storage, especially when the pages are not being server-side rendered. The challenge I'm encountering is that ...

Prevent additional clicks on the image

Currently, I am dealing with a situation where I have a list containing a jQuery handler for mouse clicks. The dilemma is that I need to insert an image into the list, but I want clicking on the image to trigger a different function than clicking elsewhere ...