Adding initial data to MongoDB in ExpressJS: What's the best way to include fixture data upon startup?

I've set up my expressjs server and mongoDB (using the mongoDB native driver and not mongoose). I want to check for existing documents in the database and add some fixture documents when the server starts, but I'm unsure where to do that.

Something along the lines of:

const hasAdmin = db.collection('users').findOne({ username: 'admin' })
if (!hasAdmin) {
  // Add some data to collection
}

app.js

const app = express()
const mongoDB = mongodb://localhost:27017/mydb

// Parse application/json
app.use(bodyParser.json())
// Parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({
  extended: false
}))
// GraphQL
app.use('/graphql',
  bodyParser.text({ type: 'application/graphql' }),
  graphqlMiddleware,
  graphqlExpress(req => ({
    schema: schema
  }))
)

// Connect to Mongo on start
db.connect(mongodb, (err) => {
  if (err) {
    console.error('Unable to connect to Mongo: ' + err)
    process.exit(1)
  } else {
    app.listen(port, () => {
      console.log('Listening on port ' + port)
    })
  }
})

module.exports = app

Answer №1

It's possible to place this functionality wherever a connection to Mongo is open.

My suggestion would be to separate your database-related tasks into a distinct class (and a separate file for that; separation of concerns).

You can then invoke the function that populates your database initially from the constructor of that class.

Here is an example (not executable code, but gives an idea):

db-helper.js

class DbHelper {
    constructor() {
        this.connect();
    }

    connect() {
        // establish mongo connection
        mongo.connect("...", (err, db) => {
            this.db = db;
            // take care of initial population
            this.ensureDatabaseIsFilled();
        });

    }

    ensureDatabaseIsFilled() {
        const hasAdmin = this.db.collection('users').findOne({ username: 'admin' })
        if (!hasAdmin) {
            // Add some data to collection
        }
    }

    /**
      * Method to retrieve data from mongo
      */
    getRandomThing() {
        return new Promise((resolve, reject) => {
            this.db.find({...}, (err, result) => resolve(result));
        });
    }
}
module.exports = DbHelper;

app.js

const DbHelper = require('./db-helper');
const dbHelper = new DbHelper();
// ....
app.get('/example', (req, res) => {
    dbHelper.getRandomThing().then(result => res.send(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

JSON with a null character

Despite spending an hour searching online, I feel a bit hesitant to ask this question. Can null characters (ascii null or \0) be used within JSON? I know they are not allowed within JSON strings, but my query is whether they can be included in the bod ...

The new Facebook login button in my app seems to be glitchy as it fails to redirect users to the appropriate page after

I am working on a web application and have successfully integrated Facebook login from developers.facebook.com. However, I am facing an issue where after the user logs in with their Facebook credentials, they are not redirected to my application. Additiona ...

JS Emphasis on Scrolling Div

I'm facing an issue with a button that opens a scrollable div. When I try to use the arrow keys on the keyboard, they do not scroll the div as expected. Interestingly, if I click anywhere on the div, then I am able to scroll using the arrow keys. I ...

Setting up flowplayer for multiple div elements: a tutorial

I have a collection of videos and I am trying to set up the player for each div that holds a video. When constructing the divs in my JavaScript code, it looks like this: <div id="player+{{$index}}"></div> // The "player" + index is generat ...

The content is not displayed in the d3 visualization

While examining the code of this visualization found at http://bl.ocks.org/mbostock/4062045, I noticed that the name from the JSON file is not displaying alongside the nodes. Even though the code includes: node.append("title").text(function(d) { return ...

The style of MUI Cards is not displaying properly

I've imported the Card component from MUI, but it seems to lack any styling. import * as React from "react"; import Box from "@mui/material/Box"; import Card from "@mui/material/Card"; import CardActions from "@mui/m ...

received an error when attempting to include my mongoose model in the database

I've been facing an issue with my mongoose model. I'm trying to pass my request body data to it and then use the create function to add it to my database. However, it's not working as expected - there are no errors and it just seems to get s ...

Guide on restricting the character count and displaying the leftover characters using PHP with Ajax

I've been working on implementing a feature to display the remaining characters in a PHP AJAX call. I was successful using JavaScript, but I'm having trouble doing it with AJAX in PHP. Can someone provide assistance? <script type="text/javasc ...

Utilizing React Recharts to create personalized tooltips

In my current project, I am looking to create a custom tooltip to replace the default one in recharts. The default tooltip that I want to change is shown below: https://i.stack.imgur.com/TjTiL.png I would like the new custom tooltip to look like this: ...

Is it possible to send an array using fetch in JavaScript?

I am attempting to use the fetch function to send an array that has the following structure: {"cards":[[189,2],[211,2],[238,2],[778,2],[985,2],[1008,2],[1073,2],[1171,2],[48886,2],[49161,2],[49164,2],[49184,1],[49356,2],[50372,2],[51722,1],[52422,2]],"her ...

An Error with jQuery Autocomplete: "Callback is not Defined"

I am currently working on a jQuery script that involves autocomplete and selecting the correct value on the client side. Here is my functional code without the selected value (it displays all username available in my JSON): $(function() { $( "#us ...

Tips for creating nested master-detail or master-detail-detail queries in Loopback

My set up includes category and category_subs in a master-detail model, with the post model being linked to category_subs. I have successfully retrieved the master-detail information for both categories, but now I am unsure of how to include the post and e ...

When using the jQuery datepicker with the minDate set to 0, any past dates entered in the text box will be automatically reset to the current date

How can I prevent users from selecting past dates in a jQuery datepicker, while keeping any existing past dates displayed as is? My current code looks like this: $("#t1").datepicker({ minDate:0 }); And the text box code is, <input type="t1" va ...

Tips for retrieving the identifier of a row in a mui datagrid when an onClick event occurs

I'm attempting to integrate a material-ui datagrid with a sql database for the purpose of enabling edits to be made via a form rather than editing individual rows and cells one by one. My goal is to pass the row's id as a parameter to a function ...

Sending SQL data to a Node.js module upon receiving a client request

Currently, I am establishing a connection to a SQL database and retrieving data on the view by using res.json. The client initiates a request - my server employs an MSSQL driver and a connection string to establish a connection with the database and fetch ...

Modify meta titles according to specific url #id

My website is built in static HTML and our server does not support PHP or C#. Can JavaScript, jQuery, Ajax, or other technologies achieve the following: If the URL is: Https://example.com/page, the meta title will display as "home page". Https://example ...

Automatically deploy an Express.js server to Google Compute Engine with PM2

I am currently managing a virtual machine that is running pm2 on Google Compute Engine. What steps do I need to take in order to automate the deployment of an express.js server from a GitHub repository? I have generated an SSH key for user login and hav ...

Disregard any unnecessary lines when it comes to linting and formatting in VSC using EsLint and Prettier

some.JS.Code; //ignore this line from linting etc. ##Software will do some stuff here, but for JS it's an Error## hereGoesJs(); Is there a way to prevent a specific line from being considered during linting and formatting in Visual Studio Code? I h ...

State is causing a conflict by allowing multiple menus to open when mapping over Menu objects

I am currently encountering an issue with my Material UI <Menu>. The problem arises when I attempt to display some data and interface functionality by mapping over a <Card>, along with adding an <IconButton> on each card that opens a menu ...

Obtain keys from an object implemented with an interface in TypeScript

Is it possible to retrieve the actual keys of an object when utilizing an interface to define the object? For example: interface IPerson { name: string; } interface IAddress { [key: string]: IPerson; } const personInAddressObj: IAddress= { so ...