How to call `findOne` function in an array which is stored in a collection in Mongoose?

Viewed 35

The model of the collection is

const clientInfo = {
  uniqueID: {
    type: String,
    required: true,
  },
  firstName: {
    type: String,
    required: true,
  },
  lastName: String,
  email: {
    type: String,
    required: true,
  },
  countryCode: String,
  phone: String,
  status: {
    type: String,
    required: true,
  },
  addedOn: {
    date: String,
    time: String,
  },
};

And this model is stored in another model

const userClient = {
  userID: {
    type: String,
    required: true,
  },
  clients: [clientInfo],
};

Now, I want to compare the email of the client with the request body i have received. I am currently doing it like this:

 await UserClient.findOne(
    { userID: validUser.userID },
    async (err, clientList) => {
      if (clientList) {
        //Check for duplicate client
        await clientList.findOne(
          { email: req.body.email },
          (err, duplicateClient) => {
            if (duplicateClient) {
              return res.status(400).send(`Client already exists!`);
            } else {
              clientList.clients.push(client);
              clientList.save();
              const response = {
                statusCode: 200,
                message: "Client added!",
                client: client,
              };
              res.send(response);
            }
          }
        );
      } else {
        const newList = new UserClient({
          userID: validUser.userID,
          clients: client,
        });
        newList.save();
        const response = {
          statusCode: 200,
          message: "Client added!",
          client: client,
        };
        res.send(response);
      }
    }
  );
});

But I am getting an error UnhandledPromiseRejectionWarning: TypeError: clientList.findOne is not a function.

What I am doing now is, finding a collection with a specific userID, and If I hot a match, i want to compare all the objects inside the array with the email, i have received on my request body. Currently, If It does not find any match in the UserClient.findOne, everything goes well, but if I have match in UserFind.findOne and i want to call the similar method in the array, I am getting the error.

How to do I get rid of this error?

Thanks in advance.

2 Answers

Try this

await UserClient.findOne(
    { userID: validUser.userID,'clients.email': req.body.email },
    async (err, clientList) => {
    if(err){
      //throw error here
    }
    console.log(clientList)
})

Corrected some issues,

  • find user by id, check if user is found then find client on the base of email in loop if found then return client exists otherwise save to User document,
  • if client not found then add new user and client
await UserClient.findOne(
    { userID: validUser.userID },
    async (err, User) => {
        // FIND CLIENT
        if (User) {
            let clientExists = false;
            for (let c in User.clients) {
                if (User.clients[c].email == req.body.email ) clientExists = true;
            }
            // ADD CLIENT
            if (clientExists) {
                User.clients.push(client);
                User.save();
                return res.send({
                    statusCode: 200,
                    message: "Client added!",
                    client: client,
                });
            }
            // CLIENT EXISTS 
            else {
                return res.status(400).send(`Client already exists!`);
            }
        } 
        // ADD NEW USER AND CLIENTS
        else {
            const newList = new UserClient({
                userID: validUser.userID,
                clients: client,
            });
            await newList.save();
            return res.send({
                statusCode: 200,
                message: "Client added!",
                client: client
            });
        }
    }
); 

I have not tested this code, let me know if you are getting any issues.

Related