Hello, I’ve been having trouble with saving an update that I make to a DB. I am able to push all the necessary data that I need into the array in which I want it to go, but when I try to save my updates (code block at very bottom) there seems to be an error.
Thank you, if you can help!
//create model. keep in mind, keys that will appear later were not added initially (may cause trouble).
let userSchema = new mongoose.Schema ({
username: String,
count: Number,
log: [{description: String, duration: String, date: String}]
})
let User = mongoose.model('User', userSchema)
//get username and return object with name and _id
app.post('/api/exercise/new-user', (req,res,next)=> {
let userName = req.body.username;
userName = new User ({
username: req.body.username
});
userName.save((err,data)=> {
if(err) {
console.log("error")
}else {
console.log(data)
}
})
res.json(userName)
next();
});
//create GET that returns array of all users in DB
app.get('/api/exercise/users', (req,res,next)=> {
User.find((err, data)=> {
if(err) {
console.log('error');
}res.json(data);
next();
})
});
//add exercises
app.post('/api/exercise/add', (req,res,next)=> {
//find by id, add description, duration, and if there's no date retrieve-&-add current date.
let description = req.body.description;
let duration = req.body.duration;
let date = req.body.date;
User.findById({_id: req.body.userId},(err, data)=> {
if (err) {
console.log("error");
}else {
data.log.push({description: description, duration: duration, date: date});
data.markModified(data.log);
data.save((err,data)=> {
if (err) {
console.log("error saving");
}else {
console.log(data);
}
})
}
})
next();
})