Contents

Express application with Mongoose

1 Environment

  • Mac OS Catalina 10.15.7
1
2
3
4
5
6
7
$ node -v
v14.17.0
$ npm -v
6.14.13
$ mongo --version
MongoDB shell version v4.4.5
...

2 Prerequisite

Create database name: “news_db” on MongoDB. See: Install MongoDB and use commands


1 Install Mongoose

At the project repository,

1
$ npm i mongoose -S

2 Set MongoDB on Node.js application

main.js

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
const mongoose = require("mongoose"),

// set database connection
mongoose.connect(
  "mongodb://localhost:27017/news_db", {useNewUrlParser: true}
)

mongoose.set("useCreateIndex", true);
// set database connection to const variable
const db = mongoose.connection;

// On database is opened, log message only one time
db.once("open", () => {
  console.log("Successfully connected to MongoDB using Mongoose!");
});

3 Create and apply article schema

models/article.js

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
// Schema for article
const mongoose = require("mongoose"), 
  articleSchema = mongoose.Schema({
    title: String,
    author: String,
    distributed: String,
    media: String,
    content: String
  });

// Apply schema for article
module.exports = mongoose.model("Article", articleSchema);

Load schema at main

main.js

1
Article = require("./models/article");

4 Save / create model and find it

4.1 Save model

New (create instance) from Article schema object and save it.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
var article3 = new Article({
  title: "title3",
  author: "author3",
  distributed: "2021-05-21",
  media: "terminal:)",
  content: "test"
})

article3.save((error, savedDocument) => {
  if (error) console.log(error);
  console.log("savedDocument------");
  console.log(savedDocument);
});

4.2 Create model

Create (new and save) from Article schema object. Intentionally contains typo for “media” element as below.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
Article.create(
  {
    title: "title4",
    author: "author4",
    distributed: "2021-05-21",
    meidatypo: "terminal;)",
    content: "test4"
  },
  function (error, savedDocument){
    if (error) console.log(error);
    console.log("createdDocument------");
    console.log(savedDocument);
  }
);

4.2 Find query

Create query and execute.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
var myQuery = Article.findOne({
  title: "title3"
}).where("author", /author3/);

myQuery.exec((error, data) => {
  if (data) {
    console.log("findOne(title3)------");
    console.log(data);
  }
  if (error) console.log(error.stack);
});

Actually, this source code create 2 records for each execution. It’s only for testing.


5 Run application

Typo against schema is detected as highlighted below.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
[nodemon] starting `node start main.js`
(node:59297) [MONGODB DRIVER] Warning: Current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.
(Use `node --trace-warnings ...` to show where the warning was created)
Server running at http://localhost:3000
Successfully connected to MongoDB using Mongoose!
findOne(title3)------
{
  _id: 60a600475cbac8e670c1e894,
  title: 'title3',
  author: 'author3',
  distributed: '2021-05-21',
  media: 'terminal:)',
  content: 'test',
  __v: 0  // typo is detected and replaced
}
createdDocument------
{
  _id: 60a60309ca1879e7a1ab0bcf,
  title: 'title4',
  author: 'author4',
  distributed: '2021-05-21',
  content: 'test4',
  __v: 0  // typo is detected and replaced
}
savedDocument------
{
  _id: 60a60309ca1879e7a1ab0bce,
  title: 'title3',
  author: 'author3',
  distributed: '2021-05-21',
  media: 'terminal:)',
  content: 'test',
  __v: 0  // typo is detected and replaced
}

Source


References