0

Im learning mongodb and I have the following question: In one Schema, I have a reference to another model - Im storing id's of books. I have a books model where I have a reference to other books - saving their id's.

The id's of 'similarBooks' I will insert manually. But id's of the books will be always in the format of

ObjectId("1234"). 

If user clicks on the name of book a query will be made - findById. However the id's I manually inserted are just strings, not ObjectId("id") so it wouldnt find the book. What is the best way to handle this? Do I then in my query take the id (the one thats just a string) and convert it to ObjectId("id") or do I not just insert manually the id as string but already convert to ObjectId. If so how? So far I just been adding data for this type of models in 3t studio.

Same question is for writing tests. If i have ids stored as strings, do I convert to the ObjectId ?

Thank you!

const bookSchema = new mongoose.Schema({
    title: {
        type: String,
        required: true
    },
    similarBooks: {
        name: {
            type: [String] //would be only 2
        },
        id: {
            type: [String]  //would be only 2
        }
    }
    ...
})
  • You can use the `mongoose.Types.ObjectId` to convert string to `ObjectId`. – prasad_ Aug 01 '22 at 03:21
  • but the schema as I understand doesnt do anything, its just defines the structure and content. so if I say: type: mongoose.Types.ObjectId, it doesnt do anything. Since Im adding those ids manually, if I just add a string, it will be still just a string despite the mongoose.Types.ObjectId –  Aug 01 '22 at 07:34
  • Instead of `findById` you can use the `findOne` method and pass the query filter, for example `{ filedName: "some value" }`. – prasad_ Aug 01 '22 at 08:20
  • I dont understand why? I do want to search with the id –  Aug 01 '22 at 12:15

1 Answers1

0

There is an answer on the advantage of saving Id as ObjectId instead of string here. Mainly it saves on space. MongoDb: Benefit of using ObjectID vs a string containing an Id?

So to answer you question, i would always convert that String id to ObjectId before adding it to your similarbooks array.

Don
  • 21
  • 2