首页 > 解决方案 > Node.js 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

在一个侧面问题上,查询子文档的效率会降低吗?我应该将确认码移到顶层还是无关紧要?

标签: node.jsmongodbmongoose

解决方案


试试这样: -

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

可以在子文档中查询。


推荐阅读