我试图在 TodoForm 中保存日期时间值,但这些值没有反映在数据库中。这是我的待办事项模型。
Todo.js
const mongoose = require('mongoose');
const { Schema } = mongoose;
const todoSchema = new Schema({
name: String,
description: String,
isDone: Boolean,
createdAt: Date,
updatedAt: Date
},
{timestamps: {createdAt: 'created_at' updatedAt: 'updated_at'}}
);
mongoose.model('todos', todoSchema);
然后按照我的 todosController 发布路线。
TodosController:
app.post('/api/todos', async (req, res) => {
const { name, description, isDone, createdAt, updatedAt} = req.body;
const todo = new Todo({
name,
description,
isDone,
createdAt,
updatedAt
});
try {
let newTodo = await todo.save();
res.status(201).send(newTodo);
} catch (err) {
if (err.name === 'MongoError') {
res.status(409).send(err.message);
}
res.status(500).send(err);
}
});
那是来自后端。接下来的代码来自前端。
TodoForm.jsx
componentWillReceiveProps = nextProps => {
// Load Contact Asynchronously
const { todo } = nextProps;
if (todo._id !== this.props.todo._id) {
// Initialize form only once
this.props.initialize(todo);
this.isUpdating = true;
}
};
render() {
const { handleSubmit, loading } = this.props;
if (loading) {
return <span>Loading...</span>;
}
return (
<form onSubmit={handleSubmit}>
<Field
name='createdAt'
component={DateTimePickerInput}
dateFormat='dd-MM-yyyy'
// dateFormat='dd-MM-yyyy H:mm'
// showTimeSelect
timeFormat='HH:mm'
placeholder=' todo createdAt...'
label='CreatedAt'
/>
<Field
name='updatedAt'
component={DateTimePickerInput}
dateFormat='dd-MM-yyyy'
// dateFormat='dd-MM-yyyy H:mm'
// showTimeSelect
timeFormat='HH:mm'
placeholder='todo UpdatedAt...'
label='UpdatedAt'
/>
<Link className='btn btn-light mr-2' to='/todos'>
Cancel
</Link>
<button className='btn btn-primary mr-2' type='submit'>
{this.isUpdating ? 'Updating' : 'Create'}
</button>
</form>
);
}
}
我期望输出,例如,当我完成待办事项表单并单击提交按钮时,“2020-09-18N14:00:30”,反映了数据库上的日期时间值,但实际输出是空的 createdAt 和 updatedAt 日期时间值。
怎么了?
我正在从 NewTodo.jsx 调用我的 api
state = {
redirect: false
};
componentDidMount() {
this.props.newTodo();
}
submit = todo => {
return this.props
.saveTodo(todo)
.then(response => this.setState({ redirect: true }))
.catch(err => {
throw new SubmissionError(this.props.errors);
});
};