一对多关系ObjectId在express typescript中的mongose mongodb中不起作用



Mongoose ObjectId不适用于外键ref

我有下面的代码,我想在其中将字符串转换为对象id,这样我就可以搜索它是数据库。

public getCstateByCountry = async (country_id: string): Promise<any> => {
const data = await Cstate.find({ country: Mongoose.Types.ObjectId(country_id) });
return data;
};

问题可能是打字脚本严格的打字问题。但我不知道为什么我总是犯这样严重的错误。

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;
}

问题是我在ICstate接口中使用了Mongoose.Schema.Types.ObjectId。

这里,Mongoose.Schema.Types.ObjectId用于模式。要使用文档,我们应该使用Mongoose.Types.ObjectId。我将接口中的国家/地区从Mongoose.Schema.Types.ObjectId更改为Mongoose.Types.ObjectId,现在一切正常。

解决方案接口:

export interface ICstate extends Document{
_id: string | number;
name: string;
country: Mongoose.Types.ObjectId;
}

最新更新