In a function I have, I'm doing some stuff with the properties of an object of type CardType
. Then, I want to be able to save those changes into my MongoDB database using the document.save()
function. However, I have my code like this:
import { Types } from 'mongoose';
import Card from '../models/Card';
static async updatePriceForCardByID(cardID: Types.ObjectId) {
const card = await Card.findById(cardID).exec();
return updatePriceForCard(card!);
}
static async updatePriceForCard(card: CardType) {
// This function needs some properties of 'card', it only updates the price of the card
const newPrice = await StarCityController.getUpdatedPriceForCard(card.name, card.number);
card.prices.push(newPrice);
card.save(); // <-- Error appears here
return Card.findById(card._id).populate({ path: 'prices' }).exec();
}
and my CardType
type like this:
import { Types } from 'mongoose';
export type CardType = {
_id: Types.ObjectId,
name: string,
prices: [Types.ObjectId],
number: string,
sku: string
}
the card.save()
function is not working anymore like it was when my code was in JS. Now, I know that I'm passing a CardType
as my parameter on my updatePriceForCard
function, and as such, instead of a mongoose Document, I'm passing a variable of a type that doesn't have a save
property in it.
My question is, what would be the best approach to tackle something like this?
CodePudding user response:
Did you tried creating a new instance of CardType before saving it?
CodePudding user response:
You will have to add the mongoose Document
type to your CardType
.
import { Types, Document } from 'mongoose';
export type CardType = {
_id: Types.ObjectId,
name: string,
prices: [Types.ObjectId],
number: string,
sku: string
} & Document
This will add all the necessary document methods to the type. Make sure to import the Document
type from mongoose, otherwise it may use the DOM-Document
type which will not work.