Mongoose model not persisting object

一曲冷凌霜 提交于 2021-01-28 05:13:44

问题


In a nutshell, I'm working on a math assessment app that takes your answers and stores them in a database and I'm having trouble adding more than one object to the backend. The Mongoose model is as such:

    const mongoose = require('mongoose');

const Algebra1Schema = new mongoose.Schema({
  user: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'user'
  },
  answers: {
    type: Object
  },
  date: {
    type: Date,
    default: Date.now
  }
})

module.exports = algebra1 = mongoose.model('algebra1', Algebra1Schema)

Here is the route:

// Submit application/json parser
var jsonParser = bodyParser.json();

router.post('/', [jsonParser, auth], async (req, res) => {

  try {
    let newTest = new algebra1({
      answers: req.body,
      user: req.user.id
    })
    await newTest.save();
    res.json(req.body);

  } catch (err) {
    console.error(err.message);
    res.status(500).send('Server error');
  }
})

module.exports = router;

Here is the update action that makes an axios POST request:

export const submit = (results, history) => async dispatch => {
  try {
    const config = {
      headers: {
        'Content-Type': 'application/json'
      }
    }
    const res = await axios.post('/api/algebra1', results, config);

    // dispatch({
    //   type: QuestionActionTypes.RESET
    // })

    dispatch(setAlert('You\;ve finished your assessment!', 'success'));
    history.push('/results');

  } catch (err) {

    console.error(err.message);
    // dispatch({
    //   type: PROFILE_ERROR,
    //   payload: { msg: err.response.statusText, status: err.response.status }
    // })
  }
}

I want to add a percentage item to the algebra1 model, that looks like this:

const Algebra1Schema = new mongoose.Schema({
  user: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'user'
  },
  answers: {
    type: Object
  },
**percent:{
    type: Number**
  date: {
    type: Date,
    default: Date.now
  }
})

When I changed the route to have a percent Number added, the request goes to the database, but the answers object and percent Number aren't included. I tried updating the route to:

 let newTest = new algebra1({
      answers: req.body.answers,
      percent: req.body.percent
      user: req.user.id
    })

I tried adding the following before the axios POST request:

 const body = JSON.stringify({ results, percent });

and using body in place of results in the axios POST request, but the same result; nothing was persisted to the database except the user.

Any ideas as to what I'm doing wrong? I thought maybe the results object I'm sending in my action isn't correct, but when I only send the answers as req.body, it goes through and the database has the answers object.

来源:https://stackoverflow.com/questions/62942419/mongoose-model-not-persisting-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!