Hello.
I have schemas
For user
let userSet = new Schema({
email: String,
password: String,
polls: []
});
For poll
let pollSchema = new Schema({
name: String,
options: []
});
When user create poll, it will be stored in Polls collections and in “polls” user field
So the problem:
I need to find a user who has in array “polls” a poll with special(unic) id
I try to do it like this:
userModel.find({"polls": {_id: request.body["id"]}}, (err, user) => {
console.log(user);
});
but it does not work
Please, suggest where to start to solve this
In what way does it not work? Do you get an error? Are you sure that request.body.[“id”] is what you expect it to be?
I’m not sure, but looking at the docs: https://docs.mongodb.com/manual/tutorial/query-arrays/
It seems like you should just be able to do
userModel.find({“polls”: request.body[“id”]}, (err, user) =>
assuming that “request.body[“id”]” is the string you’re looking for in the array
1 Like
Thanks a lot!
A still cannot match by id, but now able to match by field “name” :)))
Using this example code from documentation [https://docs.mongodb.com/manual/tutorial/query-array-of-documents/ ]
var cursor = db.collection('inventory').find({
"instock.qty": { $lte: 20 }
});
ead
January 9, 2018, 3:26pm
4
am i the only one who thinks that this sitting on the top of db queries stuff only adds unneeded complications
I’ve edited your post for readability. When you enter a code block into the forum, remember to precede it with a line of three backticks and follow it with a line of three backticks to make easier to read (using <code></code>
will not work properly). See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>
) will also add backticks around text.