I'm experiencing difficulties with Mongoose 5.10.0
Consider the following classes
Account:
export class Account {
_id: string;
email: string;
password: string;
phone: string;
address?: Address[] = [];
}
Address:
export class Address {
_id: string;
streetName: string;
zipCode: string;
city: string;
default: boolean | undefined;
}
And the appropriate DB models
Account:
import mongoose, { Schema, Document } from "mongoose";
import { Account } from "../classes/account.class";
import { addressSchema } from "./address.model";
export const accountSchema = new Schema({
_id: Schema.Types.ObjectId,
email: String,
phone: String,
password: String,
address: [addressSchema],
);
export type AccountModel = Document & Account;
export const Accounts = mongoose.model<AccountModel>("Account", accountSchema);
Address:
import mongoose, { Schema, Document } from "mongoose";
import { Address } from "../classes/address.class";
export const addressSchema: Schema = new Schema({
_id: Schema.Types.ObjectId,
streetName: String,
zipCode: String,
city: String,
default: Boolean,
});
export type AddressModel = Document & Address;
export const Addresses = mongoose.model<AddressModel>("Address", addressSchema);
Now when I get an account from the DB and try perform a pull against the address of the result, the pull()
- method is not found at all and I get Property 'pull' does not exist on type 'Address[]'.
Is there something fundamentally wrong in the way the schema's are defined? Where am I going wrong?
In your code you're expecting MongoDB's pull
operator to be a JavaScript method. You have two ways to achieve what you're trying to do:
You can either use .findOne()
to retrieve the document, use JS code to modify the array (e.g. slice
) and then run .save()
to synchronize these changes with your db.
However if pulling an address is all you want to do then you can run an update operation directly on the database:
await Accounts.update({_id: idToFind}, {"$pull": { "address": { _id: addressId } } })
You'll end up having only one database call when using this 2nd approach