【问题标题】:$pull works on mongo shell but not in nodejs(expressjs) code$pull 适用于 mongo shell 但不适用于 nodejs(expressjs) 代码
【发布时间】:2018-11-06 05:49:37
【问题描述】:

该集合包含以下文档:

{
"_id" : ObjectId("5b02df7a45b504151cb42c40"),
"email" : "micro@gmail.com",
"appointments" : [ 
    {
        "patient_name" : "patient_1",
        "patient_id" : 1.0,
        "time" : 1528915447.0
    }, 
    {
        "patient_name" : "patient_2",
        "patient_id" : 2.0,
        "time" : 1529915447.0
    }
]}

当我在robomongo工具或mongo shell上尝试时,以下操作将删除带有patient_name=“patient_2”的文档(即第二个文档)

db.getCollection('doctors').update(
{ email: "micro@gmail.com" },
{ $pull: { appointments: {patient_name: "patient_2", patient_id:2, time: 1529915447} } } 
)

但是,当我尝试使用节点 api 进行相同操作时,它只是将响应发送为 {success: true},但并未从数据库中删除该特定文档

app.post('/secure/doctor/reject_appointment', function(req, res){
    console.log(req.body)
    if(!req.user){
        res.json({success: false,message:"Unauthorized"});;
    return;
    }
    Doctor.findByIdAndUpdate(req.user.id,
        {$pull: { appointments: {patient_name: req.body.patient_name, patient_id:req.body.patient_id, time: req.body.time}}},
        {safe: true, upsert: true},
        function(err, doc) {
            if(err){
            console.log(err);
            res.json({
                success:false
                }).end();
            }else{
                console.log(doc.appointments)
                res.json({
                success:true
                }).end();
            }
        }
    );
});

请求正文:{ patient_name: 'patient_2', patient_id: 2, time: 1529915447 } 无法解决问题。

【问题讨论】:

  • 与其说你检查过,不如在这里显示它实际包含的内容。你也许能看到那里有什么,但我们不能。即使您认为没问题,我们也可能会以不同的方式思考并注意到您没有注意到的问题。 Edit your question
  • 你能检查一下你正在使用的MongoDB版本吗?
  • @CaptainJackSparrow 现在是 2.6.10
  • 你也应该在节点中使用update...并且只有一个字段patient_id可以从数组中拉取对象

标签: node.js mongodb mongoose mongo-shell robo3t


【解决方案1】:

请更新 MongoDB 版本,只有单个唯一参数可以提取数据,您的查询将起作用:另外,保持 NPM 和节点更新。

Upgrade MongoDB version to 3.2.

app.post('/secure/doctor/reject_appointment', function(req, res){
    console.log(req.body)
    if(!req.user){
        res.json({success: false,message:"Unauthorized"});;
    return;
    }
    Doctor.findByIdAndUpdate(req.user.id,
        {$pull: { appointments: {patient_id:req.body.patient_id}}},
        {safe: true, upsert: true},
        function(err, doc) {
            if(err){
            console.log(err);
            res.json({
                success:false
                }).end();
            }else{
                console.log(doc.appointments)
                res.json({
                success:true
                }).end();
            }
        }
    );
});

希望这会有所帮助。

【讨论】:

  • $pull 也可以处理多个参数。升级 MongoDB 和节点版本解决了这个问题。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-11-19
  • 2020-01-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-13
  • 2016-05-20
相关资源
最近更新 更多