通过引用集合的ID查找文档

时间:2019-09-17 15:34:13

标签: javascript node.js mongodb typescript mongoose

我有一个 AuthenticationModel 来存储身份验证信息。

import mongoose, { Schema } from 'mongoose';

const authenticationSchema: Schema = new mongoose.Schema({
    user: {
        ref: 'User',
        required: true,
        unique: true,
    },
    passwordHash: {
        type: String,
        required: true,
    },
    passwordSalt: {
        type: String,
        required: true,
    },
});

export const AuthenticationModel = mongoose.model(
    'Authentication',
    authenticationSchema
);

,并希望通过从引用的 UserModel 中传入_id来查找文档。我目前有此代码

public fetchUserAuthenticationByUserId = async ({ user, }: { user: Document }): Promise<Document> = {
    try {
        const authentication: Document | null = await AuthenticationModel.findOne({});

        if (!authentication) {
            throw new NotFoundException('User was not found.');
        }

        return authentication as Document;
    } catch (error) {
        throw error;
    }
};

要通过 user._id 访问文档,必须传递给 findOne 函数的什么?

2 个答案:

答案 0 :(得分:0)

如果我对您的理解正确,那应该可以:在type模型中将user的{​​{1}}定义为authenticationSchema

ObjectId

,当您执行user: { ref: 'User', required: true, unique: true, type: Schema.Types.ObjectId }, 时,告诉猫鼬用数据填充findOne()字段,而不仅仅是返回_id:

user

答案 1 :(得分:0)

首先,您必须将ObjectId类型添加到authenticationSchema中的用户字段中,例如type: Schema.Types.ObjectId。 然后你可以做

const authentication: Document | null = await AuthenticationModel.findOne({user: 
  new mongoose.Types.ObjectId(user._id)
});
相关问题