#Set field to null mongoose (NOT SOLVED)

12 messages · Page 1 of 1 (latest)

flint torrent
#

I can't find a way to set a field with type ObjectId to null after giving it a value

Exemple :
(in this context guild is not the discord's one but my own one)
UserModel.ts

const UserSchema = new Schema({
  userId: {type: String, required: true}
  guild: {type: Schema.Types.ObjectId, ref: "guilds", default: null}
});

type User = InferSchemaType<typeof UserSchema>;

export default model<User>("users", UserSchema);

When my user join a guild i can simply do

index.ts

import userSchema from ./UserModel.ts

const user = await userSchema.findOne(query);
user.guild = // a guild object id (_id)
await user.save()

But when my user want to leave one I can't set it back to null
index.ts

import userSchema from ./UserModel.ts

const user = await userSchema.findOne(query);
user.guild = null // I've tried 'undefined' and casting null to ObjectId
await user.save()

I get this error -> Type 'null' is not assignable to type 'ObjectId'

Is it possible or a limitation of mongoose ?

brazen condorBOT
#
  • Consider reading #how-to-get-help to improve your question!
  • Explain what exactly your issue is.
  • Post the full error stack trace, not just the top part!
  • Show your code!
  • Issue solved? Press the button!
  • Marked as resolved by OP
nocturne hawk
#

try NaN? @flint torrent

flint torrent
flint torrent
#

I'm not even sure if this is applicable in my case but that the closest i've found

flint torrent
flint torrent
#

Set field to null mongoose (NOT SOLVED)

dense raptor
#

I'm guessing you could perhaps not have any value by default (making it result to undefined instead of null), this way you could easily use the $unset operator to set it back after the value has changed.

#

But that's just a different implementation I could really think of now.

flint torrent