Mongoose - Save array of strings

3.4K    Asked by Aalapprabhakaran in Python , Asked on May 18, 2021

I am trying to save an array of strings into my Database using Mongoose.

So for that, I have declared a variable of a person schema:

var newPerson = new Person ({
    tags: req.body.tags
});

The schema itself looks like:

var personSchema = new mongoose.Schema({
  tags: Array
});

For saving, refer the following command

newPerson.save(function(err) {
    //basic return of JSON
});

With the help of Postman, I send in an array in the body but when I check the database, it only displays one entry with the array as a whole, you can refer to the screenshot:

enter image description here

Any ideas what I have to do?

Answered by Chloe Burgess

In mongoose schema array of strings, you can pass strings as follows:

var personSchema = new mongoose.Schema({
tags: [{
    type: String
}]

The Postman sends the 'array' as the string so for that you can simply verify by inspecting the kind of req.body.tags. So for that refer the following command:

console.log(typeof req.body.tags)

If the above command yields a string data type then you have to set the type of the content from Postman to JSON.



Your Answer

Answer (1)

To save an array of strings in MongoDB using Mongoose, you need to define a schema that includes an array of strings and then use that schema to create and save documents. Here's a step-by-step guide:

Step 1: Install Mongoose

First, ensure you have Mongoose installed in your project. If not, you can install it using npm:

npm install mongoose

Step 2: Connect to MongoDB

Connect to your MongoDB instance using Mongoose. Here's a basic example of how to do that:

  const mongoose = require('mongoose');mongoose.connect('mongodb://localhost:27017/yourDatabaseName', { useNewUrlParser: true, useUnifiedTopology: true })  .then(() => console.log('MongoDB connected...'))  .catch(err => console.log(err));

Step 3: Define the Schema

Define a schema that includes an array of strings. For example, let's define a schema for a User model with a field favoriteBooks which is an array of strings:

  const userSchema = new mongoose.Schema({  name: String,  favoriteBooks: [String]});const User = mongoose.model('User', userSchema);

Step 4: Create and Save a Document

Create a new document using the defined schema and save it to the database:

  const newUser = new User({  name: 'Pawan',  favoriteBooks: ['1984', 'Brave New World', 'Fahrenheit 451']});newUser.save()  .then(user => console.log(user))  .catch(err => console.log(err));

Complete Example

  Here's a complete example putting everything together:
  const mongoose = require('mongoose');mongoose.connect('mongodb://localhost:27017/yourDatabaseName', { useNewUrlParser: true, useUnifiedTopology: true })  .then(() => console.log('MongoDB connected...'))  .catch(err => console.log(err));const userSchema = new mongoose.Schema({  name: String,  favoriteBooks: [String]});const User = mongoose.model('User', userSchema);const newUser = new User({  name: 'Pawan',  favoriteBooks: ['1984', 'Brave New World', 'Fahrenheit 451']});newUser.save()  .then(user => console.log(user))  .catch(err => console.log(err));

Explanation

Schema Definition: The schema defines the structure of the documents within a collection. The favoriteBooks field is defined as an array of strings [String].

Model Creation: The model is created using the schema and represents a collection in the database.

Document Creation and Saving: A new document is created using the model and saved to the database. The save() method returns a promise, allowing you to handle the result or any errors.

This will save a document with an array of strings in MongoDB using Mongoose.

3 Months

Interviews

Parent Categories