Mongoose - 通过引用字段 _id 查找
Mongoose - find by referenced field _id
集合架构
const notificationsSchema = new mongoose.Schema({
content: {
type: String,
required: true,
maxlength: 1000
},
recipient: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User',
required: true
}
}
});
对应的数据库条目
{
"_id" : ObjectId("607c1ebc3c2e16b610d74464"),
"content" : "Test Content",
"recipient" : "607c1e2c0bb25343e53abf45" <--- Existing _id of a user
}
正在尝试按收件人字段查找
deleteUser: combineResolvers(async (_, { id }) => {
try {
const user = await User.findById(id);
console.log(user.id); <-- returns 607c1e2c0bb25343e53abf45
// Option 1
const notification = await Notification.findOne({ recipient: user.id });
console.log(notification); <-- returns null
// Option 2
const userId = mongoose.Types.ObjectId(user.id);
const notificationObjectId = await Notification.findOne({ recipient: userId });
console.log(notificationObjectId); <-- returns null
// Working alternative
const notificationAlternative = await Notification.findOne({ content: "Test Content" });
console.log(notificationAlternative); <-- returns the correct document
return true;
} catch (error) {
throw error;
}
})
澄清一下,我不是要通过收件人字段查找用户,而是要通过收件人字段查找通知文档。
为什么我无法通过收件人 ID 检索文档?我错过了什么?
错误很可能是因为执行时数据类型不同const notification = await Notification.findOne({ recipient: user.id });
。检查 user.id
的数据类型,需要转换为字符串 user.id.toString()
集合架构
const notificationsSchema = new mongoose.Schema({
content: {
type: String,
required: true,
maxlength: 1000
},
recipient: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User',
required: true
}
}
});
对应的数据库条目
{
"_id" : ObjectId("607c1ebc3c2e16b610d74464"),
"content" : "Test Content",
"recipient" : "607c1e2c0bb25343e53abf45" <--- Existing _id of a user
}
正在尝试按收件人字段查找
deleteUser: combineResolvers(async (_, { id }) => {
try {
const user = await User.findById(id);
console.log(user.id); <-- returns 607c1e2c0bb25343e53abf45
// Option 1
const notification = await Notification.findOne({ recipient: user.id });
console.log(notification); <-- returns null
// Option 2
const userId = mongoose.Types.ObjectId(user.id);
const notificationObjectId = await Notification.findOne({ recipient: userId });
console.log(notificationObjectId); <-- returns null
// Working alternative
const notificationAlternative = await Notification.findOne({ content: "Test Content" });
console.log(notificationAlternative); <-- returns the correct document
return true;
} catch (error) {
throw error;
}
})
澄清一下,我不是要通过收件人字段查找用户,而是要通过收件人字段查找通知文档。 为什么我无法通过收件人 ID 检索文档?我错过了什么?
错误很可能是因为执行时数据类型不同const notification = await Notification.findOne({ recipient: user.id });
。检查 user.id
的数据类型,需要转换为字符串 user.id.toString()