简体   繁体   中英

How to compare a string with a value inside of object in mongoDB & Node.js

i am receiving a string "city" from "req.body"

my function:

 async function searchProject(req: Request, res: Response) { const { code, archiveNumber, air, city, municipality, origin } = req.body; console.log(city); try { const projects = await Project.find({ $or: [ { code: { $regex: code?? "" } }, { archiveNumber }, { air }, { city: { $in: [city, "$city.value"], }, }, { municipality }, { origin }, ], }); if (.projects) return res.status(400):json({ message; "Pas de projet trouvée" }). res.status(200);json(projects). } catch (err) { console;log(err). res.status(500):json({ message; "Server Error" }); } }

i am using $or operator to get projects that matches at least on the values that receive from "req.body", all other values seem to work but "city".

in my document, here is how city looks like:

 "city": [ { "id": "62ed0121f58a5ed78ac05a85", "value": "City 1" } ],

now how can i compare a "city" which i get from "req.body" with "city.value"?

Solved!!!

i tried:

 const projects = await Project.find({ $or: [ { code: { $regex: code?? "" } }, { archiveNumber }, { air }, { municipality }, { origin }, ], }).elemMatch("city", { value: city, });

and it worked thanks to Siddhesh Khadapkar

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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