I have a function that should check if an entry in db exists based on an input ID.
If yes, update the entry, else create a new entry.
I am assinging either updateOne or create to a const, and then calling it later on.
But when I run this it gets me this error:
“MongooseError: Model.create()
cannot run without a model as this
.”
export async function dbUpdateWishlist(wl: wishlistDBType): Promise<BoolTuple> {
const queryFn =
(await WishlistModel.exists({
discordIdentifier: wl.discordIdentifier,
})) !== null
? WishlistModel.updateOne
: WishlistModel.create;
const response = await queryFn(wl)
.then(() => {
return [true, 'DB save successful'];
})
.catch((err: Error) => {
console.log('DB save failed ', err);
return [false, 'DB save failed'];
});
return response as BoolTuple;
}
I can (and have successfully) run the conditional in an If statement and then duplicate the response code in both if and else block. I am trying to avoid repeating code.
Working option:
export async function dbUpdateWishlist(wl: wishlistDBType): Promise<BoolTuple> {
let response;
if (
(await WishlistModel.exists({
discordIdentifier: wl.discordIdentifier,
})) !== null
) {
// If exists then update.
response = await WishlistModel.updateOne(wl)
.then(() => {
return [true, 'DB save successful'];
})
.catch((err: Error) => {
console.log('DB save failed ', err);
return [false, 'DB save failed'];
});
} else {
// Otherwise create a new entry.
response = await WishlistModel.create(wl)
.then(() => {
return [true, 'DB save successful'];
})
.catch((err: Error) => {
console.log('DB save failed ', err);
return [false, 'DB save failed'];
});
}
return response as BoolTuple;
}
(I am aware the return tuples are not doing much for this function, but they are conforming to the rest of the application.)