I create a user inside a mongo database. The model looks like the following:
import mongoose from 'mongoose';
const userSchema = new mongoose.Schema({
username: {
type: String,
required: true,
unqiue: true,
},
password: {
type: String,
required: true,
minlength: 6,
},
email: {
type: String,
required: true,
},
avatar: {
type: String,
default: 'https://via.placeholder.com/150',
},
authority: {
type: String,
enum: ['user', 'admin'],
default: 'user',
},
vCoins: {
type: Number,
default: 0,
},
vCard: {
type: Number,
default: 0,
},
married: {
type: Number,
default: 0,
},
});
const User = mongoose.model('User', userSchema);
export default User;
Now I’m using the users objects _id inside the user-state to create a socket.io connection the following way:
const socket = io('http://localhost:5000', {
query: {
userId: id,
},
})
The user-state data is being taken this way: const id = useAppSelector((state) => state.auth.user._id)
On the backend I receive the ID in this way: const userId = socket.handshake.query.userId as string
And try to create the user object again using: const user = await User.findById(id);
using the mongo model.
Which gives me the following error: Cast to ObjectId failed for value "0" (type string) at path "_id" for model "User"
What could I do in this scenario? Since it’s saved as a mongoose.Types.ObjectId in the backend database. But should be used within client and socket backend as number / string?