node.js - 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
在一个侧面问题上,查询子文档的效率会降低吗?我应该将确认码移到顶层还是无关紧要?
解决方案
试试这样: -
const user = await userModel.findOne({ 'email.confirmationCode': confirmationCode }).exec();
可以在子文档中查询。
推荐阅读
- php - ORM HasLifecycleCallbacks 不适用于抽象父类
- javascript - 比较 JavaScript 中的两个对象
- react-native - 如何在本机反应中检查一个点是否位于折线上
- twitter-bootstrap - 如何在引导管理员上设置侧边栏菜单?
- c++11 - SIGINT 未在此范围内声明
- android - 当我在 android 应用程序的另一个活动中时,Openfire 丢失消息
- vba - 在单元格中搜索特定字符串并在 excel vba 中返回的函数
- java - 使用来自不同类层次结构路由的两个字段进行映射过滤器 lambda 表达式
- c - 如何在 C 中为匿名结构声明全局变量?
- java - 对于列表中的每个,执行操作直到满足条件