Node.js猫鼬:查找一个子文档

时间:2019-12-04 03:58:51

标签: node.js mongodb mongoose

数据库模型为

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,
  }
);

我尝试查询构型代码,但始终返回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

在另一个问题上,查询子文档是否效率更低?我应该将确认代码移到顶层还是没关系?

1 个答案:

答案 0 :(得分:1)

尝试这样:-

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

可以在子文档中查询。