I am testing find() and $in where I provide an array with a list of matched names as the query input to find corresponding _id. However, I can only get one matched (the 1st one) even I have multiple matched user names in the array.
How can I return multiple matches using a list of user names as the query input? Is "$in" the right approach?
ps: I am relative new to web programming; id below are masked;
exports.getUserID = (req, res, next) => {
const namearray = req.body.name.split(',');
console.log('name array:', namearray);
const myCursor = User.find({ name: { $in: namearray } }).then(users => {
users.forEach(user => {
console.log('found user id:', user._id);
});
res.status(200).send(users);
});
};
It returns only one document as below even the namearray has 3 matched names.
[
{
"works": [],
"_id": "6xxxxxxxxxxxxx",
"name": "user1",
"email": "[email protected]",
"__v": 0
}
]
the console outputs:
name array: [ 'user1', ' user2', ' user3' ]
found user id: 6xxxxxxxxxxxxx
if I hardcode a list of name using an array (userName) as the following, it works fine.
exports.getUserID = (req, res, next) => {
const userNAME = ['user1', 'user2', 'user3'];
// const namearray = req.body.name.split(',');
const myCursor = User.find({ name: { $in: userNAME } }).then(users => {
users.forEach(user => {
console.log('found user id:', user._id);
});
res.status(200).send(users);
});
};
It returns 3 matched documents when hardcoding name array.
[
{
"works": [],
"_id": "6xxxxxxxxxxxxx",
"name": "user1",
"email": "[email protected]",
"__v": 0
},
{
"works": [],
"_id": "6xxxxxxxxxxxxx",
"name": "user2",
"email": "[email protected]",
"__v": 0
},
{
"works": [],
"_id": "6xxxxxxxxxxxxx",
"name": "user3",
"email": "[email protected]",
"passwordChangedAt": "2019-07-01T00:00:00.000Z",
"__v": 0
}
]
the console outputs:
found user id: 6xxxxxxxxxxxx1
found user id: 6xxxxxxxxxxxx2
found user id: 6xxxxxxxxxxxx3
here is my html code:
<!DOCTYPE html>
<html>
<form action="/users/getUserID" method="POST" id="getuserid" enctype="application/x-www-form-urlencoded">
<div>
<label for="name"> Enter User Name(s) (separate users by comma): </label>
<input type="text" id="name" name="name">
<button id="getuserid" type="submit"> Get ID </button>
</div>
</form>
</html>
ps: later I would then save the found user ids as an object ID array to write into another collection with a field with objectID array as its schema
CodePudding user response:
The $in
is the right approach for this. I think the problem is with the way you have splitted the namearray
. There are spaces in the result, that is why it works with the hardcoded solution.
Change this line:
const namearray = req.body.name.split(',');
to this:
const namearray = req.body.name.split(', ');
CodePudding user response:
In addition to the solution D. Zsolt pointed out, I also use map() to trim out the spaces.
const namearray = req.body.name.split(',').map(item => item.trim());