Skip to content

Commit 01e7258

Browse files
github-actions[bot]stephmarie17rachel-mack
authored
DOCSP-48893 Add get started with Mongoose tutorial (#1138) (#1187)
(cherry picked from commit f00a8e4) Co-authored-by: Stephanie <52582720+stephmarie17@users.noreply.github.com> Co-authored-by: Rachel Mackintosh <rachel.mackintosh@mongodb.com>
1 parent 47cff38 commit 01e7258

12 files changed

+1029
-0
lines changed
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
import mongoose from 'mongoose';
2+
const { Schema, SchemaTypes, model } = mongoose;
3+
4+
// start-blogSchema
5+
const blogSchema = new Schema({
6+
title: {
7+
type: String,
8+
required: true,
9+
},
10+
slug: {
11+
type: String,
12+
required: true,
13+
minLength: 4,
14+
},
15+
published: {
16+
type: Boolean,
17+
default: false,
18+
},
19+
author: {
20+
type: String,
21+
required: true,
22+
},
23+
content: String,
24+
tags: [String],
25+
comments: [{
26+
user: String,
27+
content: String,
28+
votes: Number
29+
}]
30+
}, {
31+
timestamps: true
32+
});
33+
// end-blogSchema
34+
35+
// start-blogSchema-middleware
36+
blogSchema.pre('save', function(next) {
37+
this.updated = Date.now();
38+
next();
39+
});
40+
// end-blogSchema-middleware
41+
42+
const Blog = model('Blog', blogSchema);
43+
export default Blog;
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
import mongoose from 'mongoose';
2+
const { Schema, model } = mongoose;
3+
4+
const blogSchema = new Schema({
5+
title: String,
6+
slug: String,
7+
published: Boolean,
8+
author: String,
9+
content: String,
10+
tags: [String],
11+
comments: [{
12+
user: String,
13+
content: String,
14+
votes: Number
15+
}]
16+
}, {
17+
timestamps: true
18+
});
19+
20+
const Blog = model('Blog', blogSchema);
21+
export default Blog;
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
import mongoose from 'mongoose';
2+
// start-blogSchema-import
3+
import Blog from './model/Blog.js';
4+
// end-blogSchema-import
5+
6+
mongoose.connect("<connection string>");
7+
8+
// start-insert
9+
// Creates a new blog post and inserts it into database
10+
const article = await Blog.create({
11+
title: 'Awesome Post!',
12+
slug: 'awesome-post',
13+
published: true,
14+
content: 'This is the best post ever',
15+
tags: ['featured', 'announcement'],
16+
});
17+
18+
console.log('Created article:', article);
19+
// end-insert
20+
21+
// start-update
22+
// Updates the title of the article
23+
article.title = "The Most Awesomest Post!!";
24+
await article.save();
25+
console.log('Updated Article:', article);
26+
// end-update
27+
28+
// start-find-by-id
29+
// Finds the article by its ID. Replace <object id> with the objectId of the article.
30+
const articleFound = await Blog.findById("<object id>").exec();
31+
console.log('Found Article by ID:', articleFound);
32+
// end-find-by-id
33+
34+
// start-project-fields
35+
// Finds the article by its ID and projects only the title, slug, and content fields.
36+
// Replace <object id> with the objectId of the article.
37+
const articleProject = await Blog.findById("<object id>", "title slug content").exec();
38+
console.log('Projected Article:', articleProject);
39+
// end-project-fields
40+
41+
// start-delete-one
42+
// Deletes one article with the slug "awesome-post".
43+
const blogOne = await Blog.deleteOne({ slug: "awesome-post" });
44+
console.log('Deleted One Blog:', blogOne);
45+
// end-delete-one
46+
47+
// start-delete-many
48+
// Deletes all articles with the slug "awesome-post".
49+
const blogMany = await Blog.deleteMany({ slug: "awesome-post" });
50+
console.log('Deleted Many Blogs:', blogMany);
51+
// end-delete-many
52+
53+
// start-validated-insert
54+
// Creates a new blog post and inserts it into database
55+
const article = await Blog.create({
56+
title: 'Awesome Post!',
57+
slug: 'awesome-post',
58+
published: true,
59+
author: 'A.B. Cee',
60+
content: 'This is the best post ever',
61+
tags: ['featured', 'announcement'],
62+
});
63+
// end-validated-insert
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
import mongoose from 'mongoose';
2+
import User from './model/User.js';
3+
// start-user-import
4+
import User from './model/User.js';
5+
// end-user-import
6+
7+
mongoose.connect("<connection string>");
8+
9+
// start-create-user-improper-email
10+
const user = await User.create({
11+
name: 'Jess Garica',
12+
email: 'jgarciaemail.com',
13+
});
14+
// end-create-user-improper-email
15+
16+
// start-create-user-ok-email
17+
const user = await User.create({
18+
name: 'Jess Garica',
19+
email: 'jgarcia@email.com',
20+
});
21+
// end-create-user-ok-email
22+
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
const Blog = mongoose.model('Blog', blog);
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
import mongoose from 'mongoose';
2+
import Blog from './model/Blog.js';
3+
// start-user-import
4+
import User from './model/User.js';
5+
// end-user-import
6+
7+
mongoose.connect("<connection string>");
8+
9+
// start-create-user
10+
// Create a new user
11+
const user = await User.create({
12+
name: 'Jess Garica',
13+
email: 'jgarcia@email.com',
14+
});
15+
// end-create-user
16+
17+
// start-article-with-author
18+
// Creates a new blog post that references the user as the author
19+
const articleAuthor = await Blog.create({
20+
title: 'Awesome Post!',
21+
slug: 'Awesome-Post',
22+
author: user._id,
23+
content: 'This is the best post ever',
24+
tags: ['featured', 'announcement'],
25+
});
26+
27+
console.log('Article with Author:', articleAuthor);
28+
// end-article-with-author
29+
30+
// start-populate-author
31+
// Populates the author field with user data
32+
const articlePopulate = await Blog.findOne({ title: "Awesome Post!" }).populate("author");
33+
console.log('Article Populated:', articlePopulate);
34+
// end-populate-author
35+
36+
// start-middleware-update
37+
// Uses middleware to update the updated field before saving and updating
38+
39+
// Create a new article
40+
const articleMiddlewareUpdate = await Blog.create({
41+
title: 'Another Awesome Post!',
42+
slug: 'Another-Awesome-Post',
43+
author: user._id,
44+
content: 'Here is another awesome post',
45+
});
46+
console.log('Original Article: ', articleMiddlewareUpdate);
47+
// Wait
48+
await new Promise(resolve => setTimeout(resolve, 1000));
49+
// Update the article
50+
articleMiddlewareUpdate.content = "Check my updated field"
51+
await articleMiddlewareUpdate.save();
52+
console.log('Auto-updated Article:', articleMiddlewareUpdate);
53+
// end-middleware-update
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
import mongoose from 'mongoose';
2+
const { Schema, model } = mongoose;
3+
// start-schema-example
4+
const blog = new Schema({
5+
title: String,
6+
slug: String,
7+
published: Boolean,
8+
author: String,
9+
content: String,
10+
tags: [String],
11+
comments: [{
12+
user: String,
13+
content: String,
14+
votes: Number
15+
}]
16+
}, {
17+
timestamps: true
18+
});
19+
// end-schema-example
20+
const Blog = model('Blog', blog);
21+
export default Blog;
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
import mongoose from 'mongoose';
2+
// start-validate-import
3+
import validator from 'validator';
4+
// end-validate-import
5+
const {Schema, model} = mongoose;
6+
7+
const userSchema = new Schema({
8+
name: {
9+
type: String,
10+
required: true,
11+
},
12+
email: {
13+
type: String,
14+
minLength: 10,
15+
required: true,
16+
lowercase: true
17+
},
18+
});
19+
20+
// start-middleware-definition
21+
userSchema.pre('save', function (next) {
22+
const user = this;
23+
24+
// Normalize email
25+
if (user.email) {
26+
user.email = user.email.trim().toLowerCase();
27+
}
28+
29+
// Validate email format
30+
if (!validator.isEmail(user.email)) {
31+
return next(new Error('Invalid email format'));
32+
}
33+
34+
next();
35+
});
36+
// end-middleware-definition
37+
38+
const User = model('User', userSchema);
39+
export default User;
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
import mongoose from 'mongoose';
2+
const {Schema, model} = mongoose;
3+
4+
const userSchema = new Schema({
5+
name: {
6+
type: String,
7+
required: true,
8+
},
9+
email: {
10+
type: String,
11+
minLength: 10,
12+
required: true,
13+
lowercase: true
14+
},
15+
});
16+
17+
const User = model('User', userSchema);
18+
export default User;

source/index.txt

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ MongoDB Node Driver
2929
Atlas Vector Search </atlas-vector-search>
3030
Monitoring and Logging </monitoring-and-logging>
3131
Security </security>
32+
Third-Party Integrations </integrations>
3233
Reference </reference>
3334
TypeScript </typescript>
3435
API Documentation <{+api+}>
@@ -152,6 +153,7 @@ For more information about using ODMs with MongoDB, see the following resources:
152153

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

157159
Packages

source/integrations.txt

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
.. _node-integrations:
2+
3+
==================================
4+
Third-Party Integrations and Tools
5+
==================================
6+
7+
.. contents:: On this page
8+
:local:
9+
:backlinks: none
10+
:depth: 2
11+
:class: singlecol
12+
13+
.. facet::
14+
:name: genre
15+
:values: reference
16+
17+
.. meta::
18+
:keywords: i
19+
20+
.. toctree::
21+
:titlesonly:
22+
:maxdepth: 1
23+
24+
Get Started with Mongoose </integrations/mongoose-get-started>

0 commit comments

Comments
 (0)