Storing Documents and Distributing them to Customers (Using NodeJS, Express, MongoDB, and Mongoose)

Is there a way to save files in mongoose? For instance, let's say I have a route for the POST method at /, and for the GET method at /. When posting to /, the goal is to save the uploaded file to a MongoDB database using mongoose. Then, when someone tries to access / via a GET request, the saved file should be sent back. If the file happens to be an image, how can it be displayed as an image for the client? On that note, should raw files from users be saved directly into the database or is it best practice to store them differently in MongoDB?

Answer №1

It is essential to have a schema defined for your MongoDB database. This schema can be stored in a 'SCHEMA.js' file as shown below:

  module.exports = {
         model: function(Schema) {
          return new Schema({
             _id: { type: String, index: true, unique: true },
             updateDate: { type: Date, default: Date.now },
             data: String
            })
          }
  }

Once you have the schema set up, you can use it for handling requests like this:

  router.post('/', function(req, res){
     var data = req.body.data;
     SCHEMA = require('/YOUR/SCHEMA/PATH').SCHEMA;

     SCHEMA.update({
       _id: data.id
     }, {
        data: data
     }, {
      upsert: true
      }, function (err) {
       if (err) {console.error('subs-on-userapps> failed update token, err=',err);}
     });
  })

In the above code snippet, data from the request is inserted into the MongoDB database.

The .update method searches for existing data and inserts it with the option upsert:true if it does not already exist.

To retrieve data, another route with a Get method can be set up as follows:

      router.get('/', function(req, res){

          SCHEMA.findOne({QUERY})
               .execQ()
               .then(function(result) {
                    res.json({result: result})
               });

      })

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

When attempting to send emails, SendGrid encounters an error and fails to provide an error code

Earlier today, I successfully sent out a series of emails using SendGrid. It was quite a large number of emails, as I needed to create multiple user accounts with attached email addresses. Thankfully, everything went smoothly and all the emails were delive ...

Implementing personalized static content delivery in Express.js

I am looking to implement a feature in Express where I can serve static content specific to each user. Essentially, I want to make sure that if a user is logged in, they can access their own private static folder through express. Other users should not hav ...

Node.js and Express.js fails to transmit files to clients

Attempting to send a gif to the client for future use in CSS, but encountering a 404 error in the console log. The gif is located within the public directory. Server: var app = require('express')(); var http = require('http').Server(a ...

Data is not found in req.body when making a fetch request

I have been attempting to send a fetch request to my server, but I am consistently receiving an empty req.body. Here is the client-side script: const form = document.getElementById('form1') form.addEventListener('submit', (e) => ...

I am unable to view the metrics and HTTP requests/responses data on the Azure Application Insights dashboard for my Node.js Express application

Currently integrating Azure App Insights into my NodeJS app (specifically a Remix app using Express). However, after setting up the library, I am not able to see any metrics appearing on my Application Insights Dashboard or the "Performance" tab. https:// ...

Ways to retrieve information from a URL using the .get() method in a secure HTTPS connection

As I work on handling user input from a form using node.js, express, and bodyParser, I encounter an issue. Even after using console.log(req.body), the output is {}. This is puzzling as there is data in the URL when the form is submitted successfully at htt ...

Creating an array of struct in NodeJS using Foreign Function Interface (FFI)

Is it possible to repeat C++ code using nodejs modules such as ffi, ref, ref-struct, and ref-array? CK_BBOOL yes = CK_TRUE; CK_BBOOL no = CK_FALSE; // encryption/decryption sensitive key CK_ATTRIBUTE key_template[] = { {CKA_SENSITIVE, &yes, sizeof ...

Even with the inclusion of headers in the server code, the Cross-Origin Request is still being

I have a basic API set up in Express/Node and a simple Angular application for posting blogs. However, I am encountering an issue when trying to access the /contribute route using the POST method. The error message that I receive on both Chrome and Firefox ...

Learn the process of effortlessly transferring user information to a MongoDB database

Using socket.io, I am broadcasting geolocation data (lat, lng) and updating the marker icon on a map every time a user connects to the app. When a user from Japan connects, their position is shared with me and vice versa. The issue arises when I only want ...

NodeJS: Issue when implementing try/catch with async/await causing SyntaxError

As a newcomer to Node Js, I am struggling to understand why the code below is throwing a syntax error with catch(). I recently updated to Node JS V14. Any assistance would be greatly appreciated. async function demoPromise() { try { let message ...

Contrasting characteristics of a node.js server built with http.createServer versus one created with express

Could you explain the distinction between setting up a server with the http module versus configuring a server with the express framework in Node.js? Appreciate it. ...

Incorporate the .pem data into the .env file

In my next.js application, I am facing a challenge with JWT public/private key authentication. My hosting provider does not allow me to upload secret files, so I am attempting to access the .pem file from a multi-line string stored in an .env variable. Th ...

The delivery person is not receiving a reply after making the delivery

When using Express/Node and Postgres with the 'pg' package, the following code snippet is used: const createEvent = (request, response) => { console.log(request.body); const { type, location, current_attendees ...

Steps for Incorporating Angular CLI Project with Node.js/Express.js Project

I am currently working on two projects, each housed in a different folder. The Node and Express project is located in the root folder, while the Angular CLI project can be found within the angular-src folder. I am able to run each project separately - the ...

How to optimize performance in Node/Express by ending long-running POST requests early

As a beginner in Node/Express, I am facing the challenge of managing a series of long-running processes. For example: post to Express endpoint -> save data (can return now) -> handle data -> handle data -> handle data -> another process -> ...

The internal cjs loader in node threw an error at line 1078

I'm encountering an error on Windows 10 when running the npm command: node:internal/modules/cjs/loader:1063 throw err; ^ Error: Cannot find module 'D:\mobile-version portfolio\ at Module._resolveFilename (node:internal/modules/cjs/load ...

Save the application's state of the user in a mean stack program

In my Angular 9 application, I have forms with multiple sections. The first section includes name and personal details, the second part covers primary school information, and the third part focuses on past jobs held by the user. Each part is displayed in a ...

Error TS[2339]: Property does not exist on type '() => Promise<(Document<unknown, {}, IUser> & Omit<IUser & { _id: ObjectId; }, never>) | null>'

After defining the user schema, I have encountered an issue with TypeScript. The error message Property 'comparePassword' does not exist on type '() => Promise<(Document<unknown, {}, IUser> & Omit<IUser & { _id: Object ...

Why does Chrome consider this file a document, but Firefox sees it as an image?

I am experiencing an issue with the download GET endpoint in my Express app. Currently, it reads a file from the file system and streams it after setting specific headers. Upon testing the endpoint in Chrome and Firefox, I noticed that the browsers interp ...

Mongodb Dynamic Variable Matching

I am facing an issue with passing a dynamic BSON variable to match in MongoDB. Here is my attempted solutions: var query = "\"info.name\": \"ABC\""; and var query = { info: { name: "ABC" } } However, neither of thes ...