Search code examples
node.jsmongodb

Saving ObjectId as reference does not work in NodeJs MongoDB


I am going to store a category id to an item.

I do the below .save() function to add a new row.

const myNewItem = {
    categoryId = ObjectId("5fc0a6e58dc3892120595384"),
    title = "Apple"
}
var myNewItemSave = await new Item(myNewItem).save();

However, when I check my database record

_id: ObjectId("..."),
categoryId: "5fc0a6e58dc3892120595384",
title: "Apple"

The categoryId is not saved as ObjectId.

I want to save it as ObjectId is because I am going to query some lookup aggregation like this: https://mongoplayground.net/p/50y2zWj-bQ6

so I have to make localField and foreignField are the same type as ObjectId.


Solution

  • It happen becuse your schema don't allow category id as mongoose objectId it is string

    const schema = new Mongoose.Schema(
      {
        title: { type: String },
        categoryId: { type: Mongoose.Schema.ObjectId, ref: 'categories' }
      },
      { timestamps: true, versionKey: false }
    )
    export default Mongoose.model('Items', schema)
    

    Import Item model and save will convert string into mongoose objectId

    const myNewItem = {
      categoryId: "5fc0a6e58dc3892120595384",
      title: "Apple"
    }
    const myNewItemSave = await Item.create(myNewItem);