我正在拼命地寻找存储在mongodb中的对象,以及nodejs和mongoose。
对象的模型如下所示:
const SimpleResourceSchema = new mongoose.Schema(
{
_id: String,
title: String,
objective: String,
url: String,
content: String,
active: Boolean,
type: String,
owner: String,
},
{
timestamps: true,
// _id: false,
}
);
export const SimpleResourceModel = mongoose.model<
SimpleResource & mongoose.Document
>('simpleResource', SimpleResourceSchema);
使用'id‘参数值’5f1da9737917360dd038bfc0‘进行查询:
return await SimpleResourceModel.findById(id).exec();
mongodb中存储的数据为:
{
"_id": {
"$oid": "5f1da9737917360dd038bfc0"
},
"title": "Learn cooking",
"objective": "<p>Is the fridge empty ?</p>",
"content": "...",
"url": "..",
"active": true,
"type": "simple",
"owner": "5efceb2f63b75c1750846b0a",
"createdAt": {
"$date": "2020-07-26T16:04:03.806Z"
},
"updatedAt": {
"$date": "2020-07-26T16:04:03.806Z"
},
"__v": 0
}
我四处寻找解决方案,但没有找到任何解决这个障碍的方案。
有人能帮上忙吗?
发布于 2020-08-03 19:49:50
主要问题是,当您定义模式时,您将id定义为字符串,从模式定义中删除_id: String
。并且它会自动添加。如果你想把_id添加到typescript中,你可以创建界面
export interface SimpleResource extends Document {
_id: schema.Types.ObjectId,
...
}
然后在模型中直接添加它,但是_id已经在文档接口中定义,并确保安装@types/mongoose
export const SimpleResourceModel = mongoose.model<SimpleResource>('simpleResource', SimpleResourceSchema);
发布于 2020-08-03 19:09:33
你试过了吗?
var ObjectId = require('mongoose').Types.ObjectId;
return await SimpleResourceModel.findById(new ObjectId(id)).exec();
发布于 2020-08-03 19:25:15
当我尝试时,我仍然得到一个空响应:
await SimpleResourceModel.findById(mongoose.Types.ObjectId(id)).exec()
https://stackoverflow.com/questions/63235472
复制相似问题