DEV Community

Cover image for MongoDB: Inserting Data - Series #08
Functional Javascript
Functional Javascript

Posted on

MongoDB: Inserting Data - Series #08

Intro

In the last article in the series I showed how to establish a connection to MongoDB.

Here I'll show how to interact with data using that connection object.

Here's a simple insert:

/**
@func
insert a single doc into a coll

@param {string} dbName
@param {string} collName
@param {object} o - the doc to insert into the coll
@return {Promise<object> | null} the inserted doc, or null if exception
*/
const mgInsertOne = async (dbName, collName, o) => {
  const client = await mongoAsync();
  try {
    return await client.db(dbName).collection(collName).insertOne({ ts: getDateStandardWithSeconds(), ...o });
  } catch (err) {
    console.error(err);
    return null;
  } finally {
    if (client) {
      client.close();
    }
  }
};

export default mgInsertOne;
Enter fullscreen mode Exit fullscreen mode

Here's an example usage:

 mgInsertOne("myCompanyDB", "userColl", { firstName: "fluffy" });
Enter fullscreen mode Exit fullscreen mode

Here's the sample output:

/*
@output
{
  ts: '[2021-02-09 Tue 09:21:21]',
  firstName: 'fluffy',
  _id: 6022c491834ad44058181f5b
}
*/
Enter fullscreen mode Exit fullscreen mode

Notes

The "mgInsertOne" utility func will return our inserted record. This is useful for delivering feedback in the UI.

Notice the utility func closes the client connection in the "finally" block

If the DB does not exists, it gets created dynamically.

If the collection does not exists, it gets created dynamically.

If you don't supply a primary key, which is field called, "_id", then the framework autogenerates one for you.

The client code of this func is a simple one liner. Wrap it in an Express.js route, push it to a provider like Heroku, and you're live within minutes — from composing the query — to having it available for clients to use.

What's Next?

If you have any questions let me know.

The best way to perform queries in Mongo is using their "aggregate" func. It takes an arr of objs. Each obj is a part of the query that we're composing. It's an extremely powerful command that allows to you to shape and reshape your data any way your wish.
We'll cover more real-life examples of this powerful tool.
Start reading from the beginning of this series to get an introduction to this "Aggregation Framework".

Modern auth, access control, and billing built for engineers

Modern auth, access control, and billing built for engineers

Skip the glue code. Launch faster with authentication, RBAC, and billing that live in your stack from day one.

Get a free account

Top comments (0)

Heroku

Tired of jumping between terminals, dashboards, and code?

Check out this demo showcasing how tools like Cursor can connect to Heroku through the MCP, letting you trigger actions like deployments, scaling, or provisioning—all without leaving your editor.

Learn More

👋 Kindness is contagious

Explore this insightful write-up embraced by the inclusive DEV Community. Tech enthusiasts of all skill levels can contribute insights and expand our shared knowledge.

Spreading a simple "thank you" uplifts creators—let them know your thoughts in the discussion below!

At DEV, collaborative learning fuels growth and forges stronger connections. If this piece resonated with you, a brief note of thanks goes a long way.

Okay