potato
potato

Reputation: 223

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.

Upvotes: 2

Views: 643

Answers (2)

user11897373
user11897373

Reputation:

@Ashok defines a type in the model, if you dont want to modify the model you can "convert" the id with mongoose.Types.ObjectId, eg:

const mongoose = require('mongoose')
const myNewItem = {
    categoryId = mongoose.Types.ObjectId("5fc0a6e58dc3892120595384"),
    title = "Apple"
}

Upvotes: 0

Ashok
Ashok

Reputation: 2932

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

Upvotes: 1

Related Questions