问题
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