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
0 commit comments