Mongoose findOne()在一个特定的对象属性查询中返回null



我正在尝试使用mongoose的findOne((属性搜索mongodb集合中的文档。模式如下:

用户地址的模式

const AddressSchema = new Schema({
houseNumber: { 
type: String, 
required: true },
street: { 
type: String, 
required: true },
barangay: { 
type: String, 
required: true },
city: { 
type: String, 
required: true },
province: { 
type: String, 
required: true },
zipCode: { 
type: Number, 
required: true },
})

用户收藏

const UserSchema = new Schema({
patientID: {
type: String,
required: true,
unique: true
},
username: {
type: String,
required: true,
unique: true
},
password: {
type: String,
required: true
},
firstName: {
type: String,
required: true
},
lastName: {
type: String,
required: true
},
sex: {
type: String,
required: true
},
birthdate: {
type: Date,
required: true
},
bloodType: {
type: String,
required: true
},
address: {
type: AddressSchema,
required: true
}
})

以及处理查询的代码:

static async fetchUserFiles(req, res, next) {
console.log(req.params.id);
const userData = await User.findOne({ patientID: req.params.id});
}

如果这有帮助的话,下面是URL:

router.route("/user/files/:id")
.get(checkIfAuthenticated, FileHandler.fetchUserFiles)

问题是,当我尝试按用户名搜索用户时,就像await User.findOne({username: 'johnsmith'})一样,它工作得很好。但是,当执行上述代码时,函数返回null。我已经检查了我是否给出了正确类型的查询,但它仍然给出了null。经过观察,我还尝试搜索其他文档字段,如firstNamelastName,效果很好。它只在我尝试按patientID搜索时抛出null。

非常感谢任何线索!

能否检查patientId是否为ObjectId类型,以及您试图搜索的值是否也是ObjectId类型。有时铸造会导致问题

最新更新