Reputation: 306
So I'm trying to make some realtions with mongoose. But when it comes to saving one schema to an other I get this error:
Argument passed in must be a single String of 12 bytes or a string of 24 hex characters
Here are some similar Schemas:
mongoose = require('mongoose')
const Schema = mongoose.Schema
const userSchema = new Schema({
_id: String,
role: {
type: String,
default: 'Player'
},
tags: {
type: [Schema.Types.ObjectId],
ref: 'Tag'
}
})
module.exports = mongoose.model('User', userSchema)
mongoose = require('mongoose')
const Schema = mongoose.Schema
const tagSchema = new Schema({
_id: {
type: String,
require: true
},
description: {
type: String,
require: true
},
color: {
type: String,
default: '#2476d1'
}
})
module.exports = mongoose.model('Tag', tagSchema)
And how I'm trying to link
try {
const tag = await Tag.findOne({_id: 'Noob'})
user.tags.push(tag.id)
await user.save()
} catch (err) {
console.error(`ERROR: ${user._id} at Noob check`)
console.error(err)
}
According to other posts I've also tried pushing the _id
like that:
user.tags.push(mongoose.ObjectID(tag._id))
// and
user.tags.push(mongoose.ObjectID.createFromHexString('4e6f6f62')) // just 'Noob' in hex
And I still get that error. How can I create a reference with a custom _id
?
Upvotes: 1
Views: 1017
Reputation: 22296
You just have a type mis-match, an ObjectId has certain structure restriction for Mongo. The string 4e6f6f62
does not match these restrictions.
Just change your user schema tags
field to string:
tags: {
type: String,
ref: 'Tag'
}
And just keep the creation as is without trying to cast the string into ObjectId
. If for some reason there's a specific reason you want it to be ObjectId
you'll have to re-save the tag collection and conver the _id
to a valid ObjectId
format.
Upvotes: 1