简体   繁体   English

用猫鼬查询mongodb

[英]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 ie 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 我在这里想念什么

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

save method has only e (error) in callback. save方法在回调中仅包含e (error)

Also your database structure is poorly written. 另外,您的数据库结构编写得很差。 Most of your updates must be done by mongodb but not on your node server. 您的大多数更新必须由mongodb完成,而不是在节点服务器上。

Make beds as a separate collection and give its id in client.department. 将床铺成一个单独的集合,并在client.department中提供其ID。

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. 同样,findById也可以,但是使用findOne({_ id:req.body.cid})更好。

To check if it updated just console.log(client) . 要检查它是否更新,只需console.log(client)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM