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.