【发布时间】:2021-07-13 02:33:16
【问题描述】:
Mongoose ObjectId 不适用于外键引用
我有以下代码,我想在其中将字符串转换为对象 id,以便我可以搜索它是 db。
public getCstateByCountry = async (country_id: string): Promise<any> => {
const data = await Cstate.find({ country: Mongoose.Types.ObjectId(country_id) });
return data;
};
问题可能是 typescript 严格的打字问题。但我不知道为什么我不断收到这个讨厌的错误。
Type 'ObjectId' is not assignable to type 'Condition<ObjectId>'.
Type 'ObjectId' has no properties in common with type 'QuerySelector<ObjectId>'.
此外,它不会将正确类型的数据作为 ICstate 类型返回。 由于我的时间很少,因此我们将不胜感激。
这是模型
const cstateSchema = new Schema(
{
name: {
type: String,
unique: true,
},
country: {
type: Mongoose.Schema.Types.ObjectId,
ref: 'Country'
}
},
{
timestamps: true
}
);
这是模型界面
export interface ICstate extends Document{
_id: string | number;
name: string;
country: Mongoose.Schema.Types.ObjectId;
}
【问题讨论】:
标签: node.js mongodb typescript express mongoose