Bill
Bill

Reputation: 5150

Node.js Mongoose: Find one subdocument

The database model is

const userSchema: Schema = new Schema(
  {
    email: {
      confirmationCode: { type: String, unique: true, index: true },
      confirmed: { type: Boolean, default: false },
      sentAt: { type: Date },
    },
    password: {
      hash: { type: String },
      resetCode: { type: String },
      sentAt: { type: Date },
    },
    shared: {
      avatarId: { type: String },
      email: { type: String, required: true, unique: true, index: true },
      fullName: { type: String },
    },
  },
  {
    timestamps: true,
  }
);

And I try and query the conformation code but always returns null

  static confirmEmail = async (req: Request, res: Response) => {
     try {
       const { confirmationCode } = req.body;
       console.log(confirmationCode); // logs the correct confirmation code as a string
       const user = await userModel.findOne({ email: confirmationCode }).exec();
       console.log(user); // Logs null

on a side question, is it any less efficient to query on a subdocument? Should I move the confirmation code to the top level or does it not matter?

Upvotes: 0

Views: 37

Answers (1)

Nikhil G
Nikhil G

Reputation: 2466

Try like this:-

 const user = await userModel.findOne({ 'email.confirmationCode': confirmationCode }).exec();

It's fine to query in sub document.

Upvotes: 1

Related Questions