yaxx
yaxx

Reputation: 655

Querying mongodb with mongoose

I am trying to fetch a document, update it and save it back to the db but it does not seem to be working i.e is not being saved to the db even though the result from the callback indicates that the update is successful by returning the newly updated document but on checking the db, the old version is still there. here is the query;

updateBed: (req, res) => {
    Client.findById(
        req.body.cid, (e, client) => {
            if (e) {
                console.log(e)
            } else {
                console.log(client.departments[2].beds[req.body.bedNo])
                client.departments.forEach((d, i) => {
                    if (d.name !== 'GOPD') {
                        return
                    } else {
                        d.beds[req.body.bedNo] = true
                    }
                })
                client.save((e, cl) => {
                    if (e) {
                        console.log(e)
                    } else {
                        console.log(cl.departments[2].beds[req.body.bedNo])
                        res.send(cl.departments)
                    }
                })
            }
        })
}

the first loggin before updating which is

console.log(client.departments[2].beds[req.body.bedNo])

differs from the last loggin after updating which is

console.log(cl.departments[2].beds[req.body.bedNo])

indicating that the update was saved but checking the db, am still seing the old version of the document. what am i missing here please

Upvotes: 0

Views: 40

Answers (1)

pr0p
pr0p

Reputation: 2358

client.save((e,cl)=> ....)

save method has only e (error) in callback.

Also your database structure is poorly written. Most of your updates must be done by mongodb but not on your node server.

Make beds as a separate collection and give its id in client.department.

Make the following changes

client.save( e => {if(e) console.log(e)} )

Also findById is fine, but using findOne({_id : req.body.cid}) is better.

To check if it updated just console.log(client).

Upvotes: 1

Related Questions