Home > Back-end >  MongoDB Query filter not working (NextJS)
MongoDB Query filter not working (NextJS)

Time:01-13

This error is driving me crazy, It works on api backend but not on getserversideprops, It's just a simple query where I want to get the username only.

Error

No overload matches this call.
  The last overload gave the following error.
    Argument of type '{ username: number; }' is not assignable to parameter of type 'FindOptions<Document>'.
      Object literal may only specify known properties, and 'username' does not exist in type 'FindOptions<Document>'

Query Im doing this on GetServerSideProps

const client = await clientPromise;
const db = client.db("?retryWrites=true&w=majority");
const user = await db.collection("Users").findOne({email: params[0]}, {username: 1})

enter image description here

This works on my API endpoints but im getting this error on server side props

CodePudding user response:

Related to the error message the second parameter is asking for a FindOptions<Document> type.

Try this and wrap your projection into the options documents (second parameter)

...    
const query = { email: params[0] }
const options = { projection: { username: 1 }}
const user = await db.collection("Users").findOne(query, options)
...

See also https://www.mongodb.com/docs/drivers/node/current/usage-examples/findOne/

  • Related