Creating new collection with mongoose
To create a new collection with Mongoose, you can follow these steps:
- Install Mongoose: If you haven't already, install Mongoose using npm or yarn:
npm install mongoose
- Create a Mongoose model: Create a new JavaScript file for your model, e.g.,
user.js
. In this file, import Mongoose and create a new model:const mongoose = require('mongoose');
const userSchema = new mongoose.Schema({ name: String, email: String, password: String });
const User = mongoose.model('User', userSchema);
module.exports = User;
In this example, we're creating a `User` model with three fields: `name`, `email`, and `password`.
3. **Connect to your MongoDB database**: Connect to your MongoDB database using Mongoose. You can do this by creating a new file, e.g., `db.js`, and importing Mongoose:
```javascript
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/mydatabase', { useNewUrlParser: true, useUnifiedTopology: true });
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', () => {
console.log('Connected to MongoDB');
});
In this example, we're connecting to a local MongoDB database named mydatabase
.
- Create a new collection: To create a new collection, you can use the
createCollection
method provided by Mongoose. You can do this by creating a new file, e.g.,createCollection.js
, and importing your model and thedb
connection:const User = require('./user'); const db = require('./db');
const createCollection = async () => { try { await db.createCollection('newCollection', { validator: { $jsonSchema: { bsonType: 'object', required: ['name', 'email'], properties: { name: { bsonType: 'string', description: 'Name of the user' }, email: { bsonType: 'string', description: 'Email of the user' } } } } }); console.log('New collection created successfully!'); } catch (error) { console.error('Error creating new collection:', error); } };
createCollection();
In this example, we're creating a new collection named `newCollection` with a JSON schema that requires two fields: `name` and `email`.
5. **Run the script**: Run the `createCollection.js` script using Node.js:
node createCollection.js
This will create a new collection named `newCollection` in your MongoDB database.
That's it! You've successfully created a new collection with Mongoose.