Reputation: 149
I am new to the MERN stack and I am trying to create users that have an empty queue, which will hold telephone numbers in E.164 format. I aim to populate and remove these numbers from the queue (type: Array) depending on API calls.
The issue is, I am able to update the array, but it overwrites every time the call is made, but I want it to append instead.
The part that I believe I need to amend is user.findByIdAndUpdate(req.params.id,{ '$set' : { queue : req.body.number}}
but I am unable to find the way to get it to append instead of update.
I know using .push()
will append an array, but how do I implement that within my controller?
Any help is greatly appreciated.
userController.js
var router = express.Router()
var ObjectID = require('mongoose').Types.ObjectId
var { user } = require('../models/user')
router.get('/', (req,res) => {
user.find((err,docs) => {
(!err) ? res.send(docs) : console.error('Error whilst getting documents : ' + JSON.stringify(err,undefined,2));
})
})
router.post('/new',(req,res) => {
var newRecord = new user ({
name : req.body.name,
company : req.body.company,
email : req.body.email,
password : req.body.password,
queue : []
})
newRecord.save((err,docs) => {
(!err) ? res.send(docs) : console.error('Error whilst creating new user : ' + JSON.stringify(err,undefined,2));
})
})
router.put('/addToQueue/:id', (req, res) => {
if(!ObjectID.isValid(req.params.id))
return res.status(400).send("No record exists with given id : " + req.params.id)
user.findByIdAndUpdate(req.params.id,{ '$set' : { queue : req.body.number}},(err,docs) => {
(!err) ? res.send(docs) : console.error('Error updating queue : ' + JSON.stringify(err,undefined,2));
})
})
module.exports = router
Upvotes: 0
Views: 308
Reputation: 10662
You can use $push
for that.
Try this:
user.findByIdAndUpdate(req.params.id, { '$push': { 'queue': req.body.number } }, (err, docs) => {
(!err) ? res.send(docs) : console.error('Error updating queue : ' + JSON.stringify(err, undefined, 2));
})
Upvotes: 1