猫鼬数组以错误的顺序保存,或者如果定义了数组的架构,则出现错误'对字符串的转换失败']

问题描述 投票:0回答:1
i在一个生产力应用程序上工作,其功能是人们可以从预定义项目(任务)列表中选择多个项目,以构建一组个人日常任务,并可以选择填充一个输入字段以修改该选定任务的持续时间。在我的“用户”猫鼬模式中,我具有“任务”数组,当用户完成他/她的任务选择时,他/她的任务列表将保存在他的用户详细信息下,并且默认列表不会被修改。我的问题是,当用户选择一些任务并单击“保存今天的任务”时,将具有选定对象的数组“任务”保存在数据库中,但是为每个对象保存了键/值对,我的应用程序将包含键的数组保存在一个对象和其他对象中的值。这是保存数据的示例:

// 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!

我在一个生产力应用程序上工作,其功能是人们可以从预定义项目(任务)列表中选择多个项目,以构建一组个人日常任务,并可以选择将一个输入字段填写到...

javascript arrays mongodb mongoose pug
1个回答
0
投票
如果框架没有简单的方法将这些输入作为对象数组返回,则可以在实例化用户之前使用map从单独的数组创建对象数组:
© www.soinside.com 2019 - 2024. All rights reserved.