Creating a Mongoose Schema for Storing an Array of Objects: A Real-World Example

Sat Jan 1, 2022

Here's an example of storing an array of objects in a Mongoose field with a real-world example.

Let's say you are creating a blog website, and you have a schema for a "Post" collection that has a field called "comments," which is an array of objects, each object containing properties such as "text", "author" and "date".

const mongoose = require('mongoose'); const Schema = mongoose.Schema; const commentSchema = new Schema({ text: {type: String, required: true}, author: {type: String, required: true}, date: { type: Date, default: Date.now } }); const postSchema = new Schema({ title: {type: String, required: true}, body: {type: String, required: true}, comments: [commentSchema], date: { type: Date, default: Date.now } }); const Post = mongoose.model('Post', postSchema);

This creates a new Mongoose model called "Post" with a field called "comments" that can store an array of objects, where each object must have a "text" field of type String, an "author" field of type String and a "date" field of type Date.

You can then use the Mongoose Post model to interact with the database and perform CRUD operations on the array of comments objects for a post.

const newPost = new Post({ title: "Example Post",
body: "This is an example post" }); newPost.comments.push({ text: "Nice post!", author: "John Doe" }); newPost.comments.push({ text: "I agree!", author: "Jane Smith" }); newPost.save();

In this example, we are creating a new post and saving it to the database. Then, we are adding two comments objects to the comments array field of the post and save it again.

You can also use the findOneAndUpdate, findOneAndRemove method on the Post model to interact with the post collection in the database and add, modify or remove comments from the post.

DCT Academy
Full Stack Web Development training institute in Bangalore

Launch your GraphyLaunch your Graphy
100K+ creators trust Graphy to teach online
𝕏
Best MERN Full Stack Development Course | Bangalore | Offline | Online | 100% Placements | Training Institute | Front End Course | React JS Training | Online Course India 2024 Privacy policy Terms of use Contact us Refund policy