无法将 createdAt 和 updatedAt 保存为日期时间值,也无法将后端保存为前端

IT技术 reactjs mongoose
2021-04-29 09:33:29

我试图在 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);
        });
    };
1个回答

第 1 步:将日期转换为架构中的字符串

模式

 createdAt: String,
 updatedAt: String

您可以直接存储您在发布请求中传递的数据,如果您想将其转换为所需的格式,则

第 2 步:如果您想以所需格式格式化日期,请使用时刻,然后安装时刻

npm install moment

const { name, description, isDone, createdAt, updatedAt} = req.body;
  const todo = new Todo({
        name,
        description,
        isDone,
        createdAt : moment(createdAt).format('DD-MM-YYYY HH.mm') , //change it as per your requirement 
        updatedAt : moment(updatedAt).format('DD-MM-YYYY HH.mm') ,
   });