1

I need to push the key value pair to new array and should build the mongodb $match query.

const queryFormat = (payload) => {
    delete payload.userEventId
    var query = {}
     var res = []
    for(key in payload) {
        if(typeof(payload[key])) {
       res.push({ [key]: payload[key] })
        }
        else {
            res.push({"$in" :{ [key]: payload[key] }})
        }
    }
    console.log(res[3])
    query['$match'] = {"$and" :res}
    console.log(query)    
}


const payload = {
    id :1,
    name : 'Alfred',
    location : 'moon',
    values : [{name: 'u',age:9}]
}
queryFormat(payload)

expected output

{"$match":{"$and":[{id:1},{name:"Alfred"},{location:"moon"},{"values":{"$in":[{name:"u"},{age: 9}]} }]}}

output I got

{"$match":{"$and":[{id:1},{name:"Alfred"},{location:"moon"},{"values":{"$in":[{name:"u",age: 9}]} }]}}

How to deal with it Thanks!!

1 Answer 1

1

Currently you are specifying the key as "key"

Use [] to specify that you need the value of key as the key

const queryFormat = (payload) => {
    delete payload.userEventId
    var query = {}
     var res = []
    for(key in payload) {
       res.push({ [key]: payload[key] })
    }
    query['$match'] = {"$and" :res}
    console.log(query)    
}


const payload = {
    id :1,
    name : 'Alfred',
    location : 'moon'
}
queryFormat(payload)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.