Skip to content

DOCSP-48893 Add get started with Mongoose tutorial #1138

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 15 commits into
base: master
Choose a base branch
from
47 changes: 47 additions & 0 deletions source/includes/integrations/mongoose-blogSchema-validate.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import mongoose from 'mongoose';
const { Schema, SchemaTypes, model } = mongoose;

// start-blogSchema
const blogSchema = new Schema({
title: {
type: String,
required: true,
},
slug: {
type: String,
required: true,
lowercase: true,
},
published: {
type: Boolean,
default: false,
},
author: {
type: String,
required: true,
},
content: String,
tags: [String],
createdAt: {
type: Date,
default: () => Date.now(),

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We typically recommend using Mongoose's timestamps option rather than writing your own createdAt/updatedAt timestamps, because Mongoose's timestamps also handle updating timestamps when using updateOne(), etc.

immutable: true,
},
updated: Date,
comments: [{
user: String,
content: String,
votes: Number
}]
});
// end-blogSchema

// start-blogSchema-middleware
blogSchema.pre('save', function(next) {
this.updated = Date.now();
next();
});
// end-blogSchema-middleware

const Blog = model('Blog', blogSchema);
export default Blog;
21 changes: 21 additions & 0 deletions source/includes/integrations/mongoose-blogSchema.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import mongoose from 'mongoose';
const { Schema, model } = mongoose;

const blogSchema = new Schema({
title: String,
slug: String,
published: Boolean,
author: String,
content: String,
tags: [String],
createdAt: Date,
updated: Date,
comments: [{
user: String,
content: String,
votes: Number
}]
});

const Blog = model('Blog', blogSchema);
export default Blog;
63 changes: 63 additions & 0 deletions source/includes/integrations/mongoose-get-started-blogSchema.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import mongoose from 'mongoose';
// start-blogSchema-import
import Blog from './model/Blog.js';
// end-blogSchema-import

mongoose.connect("<connection string>");

// start-insert
// Creates a new blog post and inserts it into database
const article = await Blog.create({
title: 'Awesome Post!',
slug: 'awesome-post',
published: true,
content: 'This is the best post ever',
tags: ['featured', 'announcement'],
});

console.log('Created article:', article);
// end-insert

// start-update
// Updates the title of the article
article.title = "The Most Awesomest Post!!";
await article.save();
console.log('Updated Article:', article);
// end-update

// start-find-by-id
// Finds the article by its ID. Replace <object id> with the objectId of the article.
const articleFound = await Blog.findById("<object id>").exec();
console.log('Found Article by ID:', articleFound);
// end-find-by-id

// start-project-fields
// Finds the article by its ID and projects only the title, slug, and content fields.
// Replace <object id> with the objectId of the article.
const articleProject = await Blog.findById("<object id>", "title slug content").exec();
console.log('Projected Article:', articleProject);
// end-project-fields

// start-delete-one
// Deletes one article with the slug "awesome-post".
const blogOne = await Blog.deleteOne({ slug: "awesome-post" });
console.log('Deleted One Blog:', blogOne);
// end-delete-one

// start-delete-many
// Deletes all articles with the slug "awesome-post".
const blogMany = await Blog.deleteMany({ slug: "awesome-post" });
console.log('Deleted Many Blogs:', blogMany);
// end-delete-many

// start-validated-insert
// Creates a new blog post and inserts it into database
const article = await Blog.create({
title: 'Awesome Post!',
slug: 'awesome-post',
published: true,
author: 'A.B. Cee',
content: 'This is the best post ever',
tags: ['featured', 'announcement'],
});
// end-validated-insert
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import mongoose from 'mongoose';
import Blog from './model/Blog.js';
// start-user-import
import User from './model/User.js';
// end-user-import

mongoose.connect("<connection string>");

// start-create-user
// Create a new user
const user = await User.create({
name: 'Jess Garica',
email: '[email protected]',
});
// end-create-user

// start-article-with-author
// Creates a new blog post that references the user as the author
const articleAuthor = await Blog.create({
title: 'Awesome Post!',
slug: 'Awesome-Post',
author: user._id,
content: 'This is the best post ever',
tags: ['featured', 'announcement'],
});

console.log('Article with Author:', articleAuthor);
// end-article-with-author

// start-populate-author
// Populates the author field with user data
const articlePopulate = await Blog.findOne({ title: "Awesome Post!" }).populate("author");
console.log('Article Populated:', articlePopulate);
// end-populate-author

// start-middleware-update
// Uses middleware to update the updated field before saving and updating

// Create a new article
const articleMiddlewareUpdate = await Blog.create({
title: 'Another Awesome Post!',
slug: 'Another-Awesome-Post',
author: user._id,
content: 'Here is another awesome post',
});
console.log('Original Article: ', articleMiddlewareUpdate);
// Wait
await new Promise(resolve => setTimeout(resolve, 1000));
// Update the article
articleMiddlewareUpdate.content = "Check my updated field"
await articleMiddlewareUpdate.save();
console.log('Auto-updated Article:', articleMiddlewareUpdate);
// end-middleware-update
1 change: 1 addition & 0 deletions source/includes/integrations/mongoose-model-example.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
const Blog = mongoose.model('Blog', blog);
21 changes: 21 additions & 0 deletions source/includes/integrations/mongoose-schema-example.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import mongoose from 'mongoose';
const { Schema, model } = mongoose;
// start-schema-example
const blog = new Schema({
title: String,
slug: String,
published: Boolean,
author: String,
content: String,
tags: [String],
createdAt: Date,
updated: Date,
comments: [{
user: String,
content: String,
votes: Number
}]
});
// end-schema-example
const Blog = model('Blog', blog);
export default Blog;
18 changes: 18 additions & 0 deletions source/includes/integrations/mongoose-userSchema.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import mongoose from 'mongoose';
const {Schema, model} = mongoose;

const userSchema = new Schema({
name: {
type: String,
required: true,
},
email: {
type: String,
minLength: 10,
required: true,
lowercase: true
},
});

const User = model('User', userSchema);
export default User;
2 changes: 2 additions & 0 deletions source/index.txt
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ MongoDB Node Driver
Atlas Vector Search </atlas-vector-search>
Monitoring and Logging </monitoring-and-logging>
Security </security>
Third-Party Integrations </integrations>
Reference </reference>
TypeScript </typescript>
API Documentation <{+api+}>
Expand Down Expand Up @@ -152,6 +153,7 @@ For more information about using ODMs with MongoDB, see the following resources:

- :website:`MongoDB ORMs, ODMs, and Libraries </developer/products/mongodb/mongodb-orms-odms-libraries/>`
- `Mongoose <https://mongoosejs.com/docs/guide.html>`__ official documentation
- :ref:`<node-mongoose-get-started>` tutorial
- `Prisma <https://www.prisma.io/docs>`__ official documentation

Packages
Expand Down
24 changes: 24 additions & 0 deletions source/integrations.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
.. _node-integrations:

==================================
Third-Party Integrations and Tools
==================================

.. contents:: On this page
:local:
:backlinks: none
:depth: 2
:class: singlecol

.. facet::
:name: genre
:values: reference

.. meta::
:keywords: i

.. toctree::
:titlesonly:
:maxdepth: 1

Get Started with Mongoose </integrations/mongoose-get-started>
Loading
Loading