0

I am trying desperately to find a object stored with mongodb, with nodejs and mongoose.

The model of the object looks like:

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

The query is made with 'id' parameter value '5f1da9737917360dd038bfc0':

return await SimpleResourceModel.findById(id).exec();

The data stored in mongodb is:

{
    "_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
}

I have looked around to get a solution, but have not found any solution to this roadblock.

Anyone can help ?

Euanm
  • 3
  • 1

3 Answers3

0

Have you tried?

var ObjectId = require('mongoose').Types.ObjectId; 
return await SimpleResourceModel.findById(new ObjectId(id)).exec();
AlexZeDim
  • 3,520
  • 2
  • 28
  • 64
0

i still get a null response when I try:

await SimpleResourceModel.findById(mongoose.Types.ObjectId(id)).exec()
Euanm
  • 3
  • 1
0

The main issue that when you define the schema you defined the id as string remove _id: String from schema definition. and it automatic be added. If you want to add _id to typescript you can create interface

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

}

then in model you directly add it but _id already defined in Document interface and make sure that you install @types/mongoose

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