Javascript 按引用集合的id查找文档
我有一个身份验证模型来存储身份验证信息Javascript 按引用集合的id查找文档,javascript,node.js,mongodb,typescript,mongoose,Javascript,Node.js,Mongodb,Typescript,Mongoose,我有一个身份验证模型来存储身份验证信息 import mongoose, { Schema } from 'mongoose'; const authenticationSchema: Schema = new mongoose.Schema({ user: { ref: 'User', required: true, unique: true, }, passwordHash: { type: Strin
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
);
并希望通过从引用的用户模型中输入\u 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;
}
};
public fetchUserAuthenticationByUserId=async({user,}:{user:Document}):Promise={
试一试{
常量身份验证:Document | null=await AuthenticationModel.findOne({});
如果(!身份验证){
抛出new-NotFoundException('未找到用户');
}
将身份验证作为文件返回;
}捕获(错误){
投掷误差;
}
};
要通过用户访问文档,我必须向findOne函数传递什么?如果我理解正确,这应该起作用:在
身份验证架构
模型中将用户
的类型定义为对象id
:
user: {
ref: 'User',
required: true,
unique: true,
type: Schema.Types.ObjectId
},
执行findOne()
时,告诉mongoose用数据填充user
字段,而不是只返回_id:
const authentication: Document | null = await AuthenticationModel.findOne({}).populate('user');
首先,您必须向authenticationSchema中的用户字段添加ObjectId类型,如类型:Schema.Types.ObjectId
。
然后你就可以做了
const authentication: Document | null = await AuthenticationModel.findOne({user:
new mongoose.Types.ObjectId(user._id)
});
我认为OP要求将正确的参数传递到findOne
函数中。他不想填充用户,他想通过用户Id查找一个文档