Ask a Question
Ask Question Login
Corporate Training
  1. Community
  2. Python
  3. Question
Python

Mongoose - Save array of strings

Asked by Aalap Prabhakaran May 18, 2021 4.8K views 2 answers
Share

About this question

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?

Your answer

2 Answers

Ranjana Admin JanBask Expert Latest answer

Answered on Jul 17, 2024

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.

Was this helpful?

More Python discussions

Learn & Explore

Free tutorials and interview questions from industry experts — learn the skill, then get ready to prove it.

Latest Python Blogs

Guides, tips and career advice on Python from JanBask experts.