I'm currently working on a productivity app that includes a feature where users can select multiple items from a predefined list of tasks to create their own set of daily tasks. They also have the option to adjust the duration of each selected task by filling in an input field. In my 'user' Mongoose schema, I have a 'tasks' array where the user's selected tasks are saved under their details without modifying the default task list. However, I'm facing an issue where instead of saving key/value pairs for each selected task object in the database, the app is saving an array with keys in one object and values in another. Here is an example of the current saved data:
// If defined in userSchema:
// tasks: [] // Just an empty array
// Current data structure:
"tasks": [
{
"title": [
"Title 01",
"Title 02",
],
"duration": [
10,
20,
]
}
]
// Desired data structure:
"tasks": [
{
"title": "Title 01",
"duration": 10
},{
"title": "Title 02",
"duration": 20
}
]
// If defined in userSchema:
// tasks: [tasksSchema] // Array of predefined objects
// Getting an error message
"error": {
"message": "Cast to string failed for value \"[ 'Title 01', 'Title 02' ]\" at path \"title\"",
"name": "CastError",
"stringValue": "\"[ 'Title 01', 'Title 02' ]\"",
"value": [
"Title 01",
"Title 02"
],
"path": "title",
"reason": null
}
Here is the remaining code for my model, controller, and view:
// My model
const tasksSchema = new mongoose.Schema({
_id: {
type: mongoose.Schema.ObjectId,
ref: 'Tasks',
},
title: {
type: String,
},
duration: {
type: Number,
},
});
const userSchema = new mongoose.Schema(
{
title: {
type: String,
trim: true,
required: true,
},
tasks: [tasksSchema],
},
{
timestamps: true,
});
module.exports = mongoose.model('User', userSchema);
// My controller
exports.updateUser = async (req, res, next) => {
try {
const user = await User.findOne({ _id: req.params.id });
await User.findOneAndUpdate(
{ _id: req.params.id },
req.body,
{ new: true, runValidators: true },
).exec();
if (!user) {
return res.status(404).json({
success: false,
error: 'no User found',
});
}
return res.redirect('back');
} catch (err) {
if (err.name === 'ValidationError') {
const messages = Object.values(err.errors).map((val) => val.message);
return res.status(400).json({
success: false,
error: messages,
});
}
return res.status(500).json({
success: false,
error: err,
});
}
};
// My view (Pug/Jade)
each item in user.tasksList || [] // This list is generated from a model 'Tasks'
li.sortableItem.ui-state-default.list-group-item(value=item._id id=`id_${item._id}` name="tasks")
span
input#title(type='text' name="tasks[title]" value=item.title)
span
input#duration.col-sm-2.input-sm.text-gray(type='number' name="tasks[duration]" value=item.duration)
Any insights on what I might be doing wrong would be greatly appreciated! Thanks!