Dino Geek, try to help you

How to create a schema in MongoDB?


In MongoDB, you do not actually need to create a schema ahead of time because it is a NoSQL database, which means it does not rely on a fixed structure like SQL databases do. MongoDB is a schema-less or schema-free database and it can store any kind of JSON-like documents.

However, if you are using a tool like Mongoose (an Object Data Modeling (ODM) library for MongoDB and Node.js), you can define a schema for your collections. Here’s an example:

```
const mongoose = require(‘mongoose’);

const Schema = mongoose.Schema;

const BlogPostSchema = new Schema({ title: String, body: String, date: Date
});

const BlogPost = mongoose.model(‘BlogPost’, BlogPostSchema);
module.exports = BlogPost;
```

This schema defines that the “BlogPost” collection will contain documents with fields: “title” as string, “body” as string, and “date” as date.

Then you can create a new blog post like this:

```
const BlogPost = require(‘./models/blogs’);

const newBlogPost = new BlogPost({ title: ‘MongoDB Schema’, body: ‘This is how to create a schema in MongoDB’, date: new Date(),
});

newBlogPost.save((error) => { if (error) { console.log(‘Oops, something happened’); } else { console.log(‘The blog post was saved.’); }
});
```

This will create a new document in the ‘BlogPost’ collection.

Please note that you will need to connect to the MongoDB database before running these commands. Also, the models directory or file location in the require statement may change based on the actual location in your project.


Simply generate articles to optimize your SEO
Simply generate articles to optimize your SEO





DinoGeek offers simple articles on complex technologies

Would you like to be quoted in this article? It's very simple, contact us at dino@eiki.fr

CSS | NodeJS | DNS | DMARC | MAPI | NNTP | htaccess | PHP | HTTPS | Drupal | WEB3 | LLM | Wordpress | TLD | Domain name | IMAP | TCP | NFT | MariaDB | FTP | Zigbee | NMAP | SNMP | SEO | E-Mail | LXC | HTTP | MangoDB | SFTP | RAG | SSH | HTML | ChatGPT API | OSPF | JavaScript | Docker | OpenVZ | ChatGPT | VPS | ZIMBRA | SPF | UDP | Joomla | IPV6 | BGP | Django | Reactjs | DKIM | VMWare | RSYNC | Python | TFTP | Webdav | FAAS | Apache | IPV4 | LDAP | POP3 | SMTP

| Whispers of love (API) | Déclaration d'Amour |






Legal Notice / General Conditions of Use