猫鼬findById

时间:2020-08-03 19:04:36

标签: node.js mongodb express mongoose

我正拼命寻找一个用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
}

我四处寻找解决方案,但没有找到解决此障碍的方法。

任何人都可以帮忙吗?

3 个答案:

答案 0 :(得分:0)

您尝试过吗?

var ObjectId = require('mongoose').Types.ObjectId; 
return await SimpleResourceModel.findById(new ObjectId(id)).exec();

答案 1 :(得分:0)

当我尝试时,我仍然收到null响应:

await SimpleResourceModel.findById(mongoose.Types.ObjectId(id)).exec()

答案 2 :(得分:0)

主要问题是,当您定义架构时,您将id定义为字符串会从架构定义中删除_id: String。并自动添加。 如果要在打字稿中添加_id,则可以创建界面

export interface SimpleResource extends Document {
  _id: schema.Types.ObjectId,
  ...

}

然后在模型中直接添加它,但是_id已在Document界面中定义 并确保您安装@ types / mongoose

export const SimpleResourceModel = mongoose.model<SimpleResource>('simpleResource', SimpleResourceSchema);