Reputation: 879
Update:
I want to only return all documents that fit four characters of a given username that is entered. So if I have a list of usernames and I type in mango3333, all usernames that are starting with "mang" should be returned. I used a regexp for that, and now I want to only return for example the username and the id of that document and not all fields, but it returns all fields.
An example document looks like this:
{"_id":{"$oid":"5d75299b0d01830"},
"User":
{ "username":"mango",
"userid":"8b8d25d3-3fe6-4d1c",
"token":"token",
"pw":"password",
"statusmessage":"",
"lastlogin":{"$date":{"$numberLong":"1567959451354"}},
"registered":{"$date":{"$numberLong":"1567959451354"}
}
This is my query:
const db = dbClient.db(dbName);
const regexp = new RegExp(username, "gi");
db.collection(collectionName).find({ "User.Username": regexp }, { "User.Username": 1, "User.UserID": 1, "User.Statusmessage": 1 })
.toArray()
.then(result => {
console.log(result);
})
.catch(err => console.error(`Failed to get results: ${err}`));
What am I doing wrong?
Upvotes: 1
Views: 598
Reputation: 3431
The 2nd portion of the find
method is an options object, not just projection. The projection portion of the query will need to be specified in this options
object. Try the following:
db.collection(collectionName).find(
{ "User.Username": regexp },
{
projection: {
"User.Username": 1,
"User.UserID": 1,
"User.Statusmessage": 1
}
}
)
.toArray()
.then(result => {
console.log(result);
})
See https://mongodb.github.io/node-mongodb-native/3.3/api/Collection.html#find
Upvotes: 6