MongoDB检查文档/记录是否存在

时间:2019-02-28 20:23:34

标签: javascript mongodb

我正在尝试将.find({})与mongogb一起使用,不幸的是它没有给我期望的响应,我不确定如何检查文档是否存在?我想做的是说:

如果文档确实存在,请执行某些操作。IE将响应发送回 但是如果不存在文档,则创建该文档,

不幸的是,我知道一个文档不存在,但是它肯定是用'if(docs)'来拾取错误的东西,但是当我将其更改为其他内容时,它总是会创建记录!?

代码:

addRefund : (refundCalc, callback) => {
    order_number = refundCalc.refundDetails.customer_details.order.order_number;
    dbconnect.createConnection()
    refund.find({order_number: order_number}, (err, docs) => {
        if (docs) {
            console.log('docss!!!!!!!!!!!!!' + JSON.stringify(docs));
            console.log('calling within error!!!!!!')
            let notStored = {"refundDocStored" : "False"}
            callback(notStored)
            dbconnect.closeConnection();
        }
        else {
            refund.create(refundCalc).then((refunddoc) => {
               let filestored = {"refundDocStored" : "True"}                              
               dbconnect.closeConnection();
               callback(filestored)
            }).catch((err)=> {
                console.log(err);
                dbconnect.closeConnection();
            })
        }
    })
},

架构:

const refundSchema = new Schema({
domain : { type: String},
refundDetails : {
    customer_details : [],
    refund : {
        shipping : {
            amount : { type: Number},
            tax : {type : Number},
            maximum_refundable : {type : Number}
        },
        refund_line_items: [],
        transactions: []   
    }
}

});

订单存储在退款详细信息中,如下所示:

"refundDetails":{"customer_details":{"order":{"order_number":1021

它似乎根本不适合我!如果文件存在,我似乎无法真正证明它确实存在?

任何帮助都会很棒,谢谢!

1 个答案:

答案 0 :(得分:0)

您使用了错误的搜索查询。您正在搜索order_number,它是另一个对象内部的一个对象的属性。您必须在查询中引用order_number完整路径,即{"refundCalc.refundDetails.customer_details.order.order_number" : order_number}

addRefund : (refundCalc, callback) => {
    order_number = refundCalc.refundDetails.customer_details.order.order_number;
    dbconnect.createConnection()
    refund.find({"refundCalc.refundDetails.customer_details.order.order_number": order_number}, (err, docs) => {
        if (docs) {
            console.log('docss!!!!!!!!!!!!!' + JSON.stringify(docs));
            console.log('calling within error!!!!!!')
            let notStored = {"refundDocStored" : "False"}
            callback(notStored)
            dbconnect.closeConnection();
        }
        else {
            refund.create(refundCalc).then((refunddoc) => {
               let filestored = {"refundDocStored" : "True"}                              
               dbconnect.closeConnection();
               callback(filestored)
            }).catch((err)=> {
                console.log(err);
                dbconnect.closeConnection();
            })
        }
    })
},