Understanding Modeling Relationships in NoSQL Database - Part Two

In the first part of this article series we completed NodeJs Implementation of Normalisation In NoSQL database, Next, we are going to start from here

NodeJs Implementation of Denormalisation In NoSQL database

const mongoose = require("mongoose");

mongoose
  .connect("localhost:dbmodel.db", {
    useUnifiedTopology: true,
    useNewUrlParser: true,
    useCreateIndex: true,
  })
  .then(() => console.log("Connected to MongoDB..."))
  .catch((err) => console.error("Could not connect to MongoDB...", err));

const userSchema = new mongoose.Schema({
  name: String,
  email: String,
});

const User = mongoose.model("User", userSchema);

const Post = mongoose.model(
  "Post",
  new mongoose.Schema({
    title: String,
    body: String,
   user: userSchema,
  })
);

async function createPost(title, body, user) {
  const post = new Post({
    title,
    body,
    user,
  });
  const result = await post.save();
  console.log(result);
}

async function listPosts() {
  const posts = await Post.find().select("name author");
  console.log(posts);
}

const updatePost = async (postId) => {
  const post = await Post.findById(postId);
  post.user.name = "Tayo shittu";
  post.save();
  console.log(post)
};

createPost(
  "Node Course",
  "NodeJs Implementation of Denormalisation In NoSQL database",
  { name: "shittu", email: "shittu@gmail.com" }
);

//listPosts();
//updatePost("5fed786117775f6d6fb4993f")

At the initial phase of the file, we connect to our MongoDB database, followed by creating the user schema,

In the Post schema, we embedded the full user schema, this way once the post document is created, the full user collection is added to the document.

In the createPost() function, we pass the title, body, and a new user collection with the name and email.

When you run the node test.js with createPost() uncommented, you should get this.

{
  _id: 5fed786117775f6d6fb4993f,
  title: 'Node Course',
  body: 'NodeJs Implementation of Denormalisation In NoSQL database',
  user: {
    _id: 5fed786117775f6d6fb49940,
    name: 'shittu',
    email: 'shittu@gmail.com'
  },
  __v: 0
}

As you can see we have the full user collection in the post document, this way we don't have to make any additional query to fetch the user detail, once query and we have the full post and user details. Having the full user details on the post document is all that denormalization relationship gives you.

When you comment out createPost() and uncomment listposts() function, then run node test.js, you should get this

[
     {
    _id: 5fed786117775f6d6fb4993f,
    title: 'Node Course',
    body: 'NodeJs Implementation of Denormalisation In NoSQL database',
    user: {
      _id: 5fed786117775f6d6fb49940,
      name: 'shittu',
      email: 'shittu@gmail.com'
    }
  },
  {
    _id: 5fed79f696ccc170188c99cc,
    title: 'Hash Node',
    body: 'asych and await',
    user: {
      _id: 5fed79f696ccc170188c99cd,
      name: 'tayo',
      email: 'tayo300@gmail.com'
    }
  }
]

the listposts() function, select only the title, body, and user in the post document, with one query we get full post details and the user that create it.

if you want to change the user name that creates a given post,

updatePost(PostId) function collect postId as an argument, use it, and find the post, then change the user name as written in the code above.

comment createPost() and listposts(), then uncomment updatePost(postId), run node test.js You get this result in the console

  {
  _id: 5fed786117775f6d6fb4993f,
  title: 'Node Course',
  body: 'NodeJs Implementation of Denormalisation In NoSQL database',
  user: {
    _id: 5fed786117775f6d6fb49940,
    name: 'Tayo shittu',
    email: 'shittu@gmail.com'
  },
  __v: 0
}

Note: we don't have post.user.name.save().

With post.save(), our name will be saved and the updated document is shown in the console.

So there you have it. this is the end of this two-part article,

If you have any question, please drop it in the comment section, let solve the elegant way. Read Part One Here