Hi campers,
I’ve been wrestling with the Issue Tracker in Quality Assurance, and I think I’m missing some core concept about editing/updating a subdocument in a document.
I am using Mongoose over MongoDB, so maybe that makes a difference. The way I’ve structured the schema is that each project has a ‘caselog’ array of issue objects. (I initially didn’t understand that the issues themselves were a sub-component of project, and that took me a while to understand).
I can’t get the API route DELETE and PUT to pass the tests. I think what is tripping me up is the editing of the array inside the of the project, and then how to “save” that back to the database.
Here is the Schema and setup:
//building a new Schema
const Schema = mongoose.Schema;
const issueSchema = new Schema({
project: {type:String, required: true},
caselog: [
{issue_title: {type:String, required: true},
issue_text: {type:String, required: true},
created_by: {type:String, required: true},
created_on: Date,
updated_on: Date,
assigned_to: {type: String, default: ''},
open: {type: Boolean, default: true},
status_text: {type: String, default: ''}
}
]
})
//building a new model from the schema
const Issue = mongoose.model('Issue', issueSchema);
Here’s a sample of the DELETE route:
.delete(function (req, res){
let project = req.params.project;
const issueId = req.body._id;
if (issueId === null){
return res.json({error: 'missing _id'});
} else {
//find item
//slice from caselog list to remove
//then save the data[0] again
model.find({project:project}).exec(function(err,data){
if (err) return (err);
for (let element of data[0].caselog){
const elementId = element._id.toString();
if (elementId === issueId){
//finds Id
const elementIndex = data[0].caselog.indexOf(element);
const removedItem = data[0].caselog.splice(elementIndex, 1);
return data[0].save(function(err, result){
if(err) return (err);
res.json({result: 'successfully deleted', _id: issueId});
})
}
}
return res.json({error: 'could not delete', _id: issueId});
})
}
});
Here’s my Repl.it:
Some general questions:
- In what instances should I be using MongoDB versus Mongoose?
- Are there built-in methods in Mongoose that allows me to update a subdoc directly? I feel like I’m relying back on JS data structures to compensate for my lack of Mongoose knowledge, and it’s not very efficient.
- I also know that I haven’t written the functional tests yet, and that may help me pinpoint why the code doesn’t pass the tests.