Trusted answers to developer questions

How to create one or many documents at once in Mongoose

Free System Design Interview Course

Many candidates are rejected or down-leveled due to poor performance in their System Design Interview. Stand out in System Design Interviews and get hired in 2024 with this popular free course.

Overview

Sometimes you may want to create a document in the MongoDB database using Mongoose ORMObject-relational mapping in computer science is a programming technique to convert data between incompatible type systems using object-oriented programming languages (Wikipedia). It can be a single document or many at once, which we can create through the Model.create() or create() method of Mongoose.

This method is very useful, as we will see in the example below.

Model.create() syntax

We can create one or more documents with this method. When you want to create a single document, an object document is passed as an argument.

To create many documents, an array of these documents is passed.

Example

In the example below, we are going to demonstrate the power of the Model.create() method.

Step 1: Set up your Node.js server

Make sure to create your server file and connect to your MongoDB database. Install mongoose, dotenv, and express.

require('dotenv').config();
const express = require('express');
const app = express();
const mongoose = require("mongoose");
mongoose.connect(process.env.DB_URL, {
useNewUrlParser: true,
});
const db = mongoose.connection;
db.on("error", () => {
console.error.bind(console, 'MongoDB connection error:')
})
db.on("open", () => {
console.log("database running successfully");
})
const port = process.env.PORT || 3000;
app.listen(port, function() {
console.log(`Listening on port ${port}`);
});

Step 2: Create a schema

The Friend schema only has the name and title fields.

const Friend = mongoose.model("Friend",
new mongoose.Schema({
name: String,
title: String
})
)

Step 3.1: Create a single document

Now, let’s create a function to create a single document.

const createSingleDocument = async () => {
try {
await Friend.deleteMany({});
let friend = await Friend.create({
name: "Theodore Kelechukwu Onyejiaku",
title: "MERN Stack Developer"
})
return friend
}
catch (error) {
throw error
}
}

The line of code below clears all previous documents in our database.

await Friend.deleteMany({});

After this, lines 5 to 6 create the new Friend document. Finally, the function returns the created document with the return statement.

Step 3.2: Create many documents at once

With the function below, many documents are created instantly.

const createManyDocuments = async () => {
try {
let friends = await Friend.create(
[
{
name: "Chidera Ndukwe",
title: "Network Administrator"
},
{
name: "Elijah Azubuike",
title: "Backend Developer"
},
{
name: "Emeka Isiolu",
title: "Web Developer"
}
]
)
return friends
}
catch (error) {
throw error
}
}

The function above is almost the same as createSingleDocument(). The only difference is that it takes an array of documents.

Step 4: Make our get request

Now we will call these functions inside of the request to get "/".

app.get("/", async (req, res) => {
let single = await createSingleDocument();
let many = await createManyDocuments();
res.json({ single, many });
});

In the code above, when we make a get request to "\", the output will be as follows:

{
"single": {
"name": "Theodore",
"title": "MERN Stack Developer",
"_id": "615757eb12aad682b4931ff0",
"__v": 0
},
"many": [
{
"name": "Chidera",
"title": "Network Administrator",
"_id": "615757eb12aad682b4931ff2",
"__v": 0
},
{
"name": "Elijah",
"title": "Backend Developer",
"_id": "615757eb12aad682b4931ff3",
"__v": 0
},
{
"name": "Emeka",
"title": "Web Developer",
"_id": "615757eb12aad682b4931ff4",
"__v": 0
}
]
}

RELATED TAGS

mongoose
mongodb
create

CONTRIBUTOR

Theodore Kelechukwu Onyejiaku
Did you find this helpful?