javascript

How to create and save schema array of strings in Mongoose


In this article, you will learn about how to create and save a schema array of strings in Mongoose.

Mongoose is an ODM(Object Data Modeling) library for MongoDB and it lets you create a schema model and save documents in MongoDB. In the Mongoose schema model, you can create an array of strings. To create it is as simple as defining a single type in the mongoose schema. Let’s see the below code example where we have created a student schema and also use array of strings.


const mongoose = require('mongoose')

const studentSchema = new mongoose.Schema({
    name : {
        type : String
    },
    age : {
        type : String
    },
    courses : [{
        type: String
    }]
})

const Student = mongoose.model('Student',studentSchema)

module.exports = Student

You can see that we have created a schema array of strings in the course’s portion. Because a student may have multiple courses and this is how you can create a schema array of strings in Mongoose.

Let’s move on to the next part where you can save a schema document that has an array of strings. To do so follow the below code. Let me assume that, you have already known how to create a basic server and connection of MongoDB atlas and other basic stuff.

router.post('/student', async (req,res,next) =>{
  let {name,age,courses} = req.body 
  try{
      let student = new Student({
          name,
          age,
          courses
      })
     let newStudent = await student.save()
     res.status(200).json({
       status: 'Success',
       data : student
     })
  }catch(err){
      console.log(err)
      next(err)
  }
})

Here, we are just showing you how you can save a document that contains an array of strings, and you can see that it is not different from creating a document that does not contain an array of strings. Let’s create a student and see what happens. To create data we are using postman.

In postman, we have sent a post request in a specific route with the credentials along with the courses array. We have also set a 200 status code and let’s check the output in the postman:

You can see that it shows success status with the information that we have provided and also generated a unique ID for us. Now let’s check it into the MongoDB database in the below:

Here, the data has been saved successfully in the MongoDB database and the type of courses has shown as an Array. This is how you can create and save a schema array of strings in Mongoose.


Share on social media

//