Updating an Array of objects within an array of objects in Javascript (NodeJS example)

Richard Soriano
3 min readSep 22, 2020

Using map, filter, splice to add, delete and find and update an array of objects with Javascript on the server side.

javascript array of objects within an array of objects.

What if Hogwarts had a website for professors to post homework assignments?

Each professor could post their assignment online for students. This would beneficial in case there’s a pandemic at Hogwarts. Let’s take a look at what database schema as well as server side javascript would look like. The professors would like to get all, get by specific ID, add, and delete.

If one were to program this in NodeJS using Express and Mongo on the server side, this is what the architecture would begin to look like.

Mongoose Schema

Let’s start with Posts. This is what a model schema using mongoose.

//  ./models/assignment.js 
const mongoose = require(‘mongoose’);
const Schema = mongoose.Schema;
const AssignmentSchema = new Schema([
professor: { type: string, required: true },
name: { type: string, required: true },
text: { type: String, required: true });
module.exports = Assignment= mongoose.model(‘assignment’, AssignmentSchema);

As you can see, the assignments would be an array of objects. ‘assignment.js’ which will be used for the mongoose model and placed in ‘./models’ folder for best practices.

For the professor type, it’s of type string for simplicities sake. Ideally, we would want to have it reference a separate collection of professors and students, which we will tackle in the upcoming posts.

Server Side

To get all of them, a simple find() command from the mongoose model. It’s placed in the ‘ ./routes’ folder.

const Assignment = require('/models/Assignment');
const assignments = Assignment.find();

The find() returns an array of objects in JSON format.

assignments : [{
professor: 'Snape',
name: 'Potion',
body: 'Create a love Potion by next week'},
{
professor: 'Professor Sprout',
name: 'Replanting',
body: 'Replant the baby Mandrakes without passing out'
},{
professor: 'Professor McGonagall',
name: 'Owl Preparation',
body: 'Wizards of the North in the Middle Ages'
}];

To get a specific assignment use the model schema object Assignment and findById(id). ‘id’ would be for the assignment that is passed from the client.

Assignment.findById(id);

To add an assignment, first create an instance of an object. Then use save()

const newAssignment = new Assignment({
professor: ‘Professor Trelawney',
name: ‘Tea Cup Predictions’,
body: ‘Quidditch score predictions using tea cups’ });
newAssignment.save();

To delete an assignment, find by assignmentID then remove it.

const assignment = Assignment.findById(id); assignment.remove();

A full example would be a nodejs server that receives gets, posts, puts, and deletes from a client. Using Javascript, Express Router and Mongoose it would look like this.

./models/Assignment.js’

const Schema = mongoose.Schema;
const AssignmentSchema = new Schema({
professor: {
type: String,
required: true},
name: { type: String,
required: true
},
body: {
type: String,
required: true}
});
module.exports = Assignment = mongoose.model('assignment', AssignmentSchema);

‘./routes/assignments.js’

const express = require('express');
const router = express.Router();
const Assignment = require('../../models/Assignment');
// @desc Create an assignment
router.assignment('/', (req, res) => {
try {
const newAssignment = new Assignment({
teacher: req.body.text,
name: user.name,
body: user.avatar
});
const assignment = newAssignment.save();
res.json(assignment);
} catch (err) {
res.status(500).send('Server Error');
}});
// @desc Get all assignment
router.get('/', (req, res) => {
try {
const assignments = Assignment.find();
res.json(assignments);
} catch (err) {
res.status(500).send('Server Error');
}});
// @desc Get assignment by id
router.get('/:id', (req, res) => {
try {
const assignment = Assignment.findById(req.params.id);
if (!assignment) {
return res.status(404).json({ msg: 'Assignment not found' });}
res.json(assignment);
} catch (err) {
console.log(err.message);
res.status(500).send('Server Error');
}});
// @desc Delete assignment by id
router.delete('/:id', (req, res) => {
try {
const assignment = Assignment.findById(req.params.id);
if (!assignment) {
return res.status(404).json({ msg: 'assignment not found' });
}
assignment.remove();
res.json(assignment);
} catch (err) {
console.log(err.message);
res.status(500).send('Server Error');
}});

This is an example of the simplicity and elegance of how javascript and mongoose fit so well together.

What if the Hermione wanted to add more features such as ‘liking’ an assignment? and Ron wanted to ‘unlike’ any assignments? Next blog…

--

--

Richard Soriano

Passion for Web Developing. Specializing in Front-End such as React, Redux and expanding to the Back-End with NodeJS to MongoDB and GraphQL