I'm trying to update a property in a MongoDB document that's in an embedded array. The JSON response shows that the field has been updated, but it's not storing that result in the database.
Here are my schemas;
const mongoose = require('mongoose')
const Schema = mongoose.Schema
let coinSchema = new mongoose.Schema({
id: {
type: String
},
name: {
type: String
},
amount_owned: {
type: Number,
default: 0
},
}, {
timestamps: true
})
let Coin = mongoose.model('Coin', coinSchema)
module.exports = Coin;
let userSchema = new mongoose.Schema({
name: {
type: String
},
email: {
type: String,
required: true
},
list: []
})
let User = mongoose.model('User', userSchema);
module.exports = User;
and my controller update method;
function update(req, res, next) {
User.findOne({
_id: req.params.id
}, function(err, user) {
if (err) return console.log(err)
for (let i = 0; i < user.list.length; i++) {
if (user.list[i].id === req.body.coinId) {
user.list[i].amount_owned = req.body.amount_owned
}
}
user.update(function(err, user) {
if (err) return console.log(err)
res.json(user.list)
})
})
}
I'm using postman and specifying the updated 'amount_owned' field in the put request body, but I'm unable to save the result in the database, even though the JSON response shows that field has been updated.
via Aaron Goldsmith
No comments:
Post a Comment