// if defined in userSchema:
// tasks: [] // just empty array
// what i get now:
"tasks": [
{
"title": [
"Title 01",
"Title 02",
],
"duration": [
10,
20,
]
}
]
// what i need:
"tasks": [
{
"title": "Title 01",
"duration": 10
},{
"title": "Title 02",
"duration": 20
}
]
// if defined in userSchema:
// tasks: [tasksSchema] // array of predefinied objects
// i got just 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
}
这是我的其余代码(模型,控制器,视图):
// 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)
我在做什么错?很多thnx!
我在一个生产力应用程序上工作,其功能是人们可以从预定义项目(任务)列表中选择多个项目,以构建一组个人日常任务,并可以选择将一个输入字段填写到...