How to put Code in your blog/article
For programmers, who want to write about their codes. Its often the first…
May 06, 2020
Mongoose provides a simple schema based solution to model your app-data. In this post, we will see how we can sue it to write basic CRUD operations in Nodejs.
First lets write a mongoose schema for a sample requirement. Example entity is Team, where I want to save:
First lets take a look on how the JSON data will look like:
{
name: "My Super Team",
createdBy: "[email protected]",
members: [
{
email: "[email protected]",
role: "admin"
},
{
email: "[email protected]",
role: "user"
},
{
email: "[email protected]",
role: "admin"
}
]
}
Lets write it in mongoose schema language.
'use strict';
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const timestamps = require('mongoose-timestamp');
const TeamMemberSchema = new Schema({
email: String,
role: String
});
TeamMemberSchema.plugin(timestamps);
const TeamSchema = new Schema({
name: String,
createdBy: String,
members: [TeamMemberSchema]
}, {
w: 'majority',
wtimeout: 10000,
collation: { locale: 'en', strength: 1 }
});
TeamSchema.plugin(timestamps);
module.exports = mongoose.model('Team', TeamSchema);
The model above is self explanatory. I have used a timestamp plugin for mongoose, which will automatically put two fields:
Also, I have used a nested schema in above example. There is another important thing to see is that I have not defined _id field. Mongoose will automatically create this, if I have not mentioned it in my schema. I can also define how I would want my _id field to be generated.
add(args) {
if (!args.name || !args.email) {
return Promise.reject(new Error('Paass team name and creator email'));
}
//using winston logging
logger.log('info', 'Adding team', {name: args.name, createdBy: args.email});
let obj = new Team();
obj.name = args.name;
obj.createdBy = args.email;
obj.members = [{
email: args.email,
role: args.role
}];
return obj.save();
}
Above code is pretty simple. You can add more robust checks, and error conditions. You might want to set data in cache.
There are several ways you can update your record, it all depends on your need. Lets see few simple examples:
Say, we want to update team name.
By loading complete object
updateTeam(teamId, teamName) {
return Team.findById(teamId)
.then(team => {
if (!team) {
return Promise.reject(new Error('Team not found'));
}
team.name = teamName;
return team.save();
});
return Team.upate({_id: args.teamId}, {
}
By NOT loading complete object
updateTeam(teamId, teamName) {
return Team.upate({_id: args.teamId}, {
name: teamName
});
}
There are bunch of options to do update. You might want to see various options in mongoose documentation.
getById(teamId) {
return Team.findById(teamId)
}
delete(teamId) {
return Team.deleteOne({_id: teamId})
}
The examples above are simple and easy to understand. Let me know if if you have some comments.
For programmers, who want to write about their codes. Its often the first…
While dealing with ELastic Search documents, you faced this issue while updating…
According to Microsoft, Therefore, they recently posted about a feature in beta…
Introduction In previous posts, we saw how to build FIPS enabled Openssl, and…
Introduction Suppose you have a view, and you have configured your display as a…
Introduction Drupal provides a powerful comment module, which comes as a part of…
Introduction In this post we will see following: How to schedule a job on cron…
Introduction There are some cases, where I need another git repository while…
Introduction In this post, we will see how to fetch multiple credentials and…
Introduction I have an automation script, that I want to run on different…
Introduction I had to write a CICD system for one of our project. I had to…
Introduction Java log4j has many ways to initialize and append the desired…