Sometimes you may want to create a document in the MongoDB database using Mongoose Model.create()
or create()
method of Mongoose.
This method is very useful, as we will see in the example below.
Model.create()
syntaxWe 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.
In the example below, we are going to demonstrate the power of the Model.create()
method.
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}`);});
The Friend
schema only has the name
and title
fields.
const Friend = mongoose.model("Friend",new mongoose.Schema({name: String,title: String}))
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.
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.
get
requestNow 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}]}