Skip to content

Instantly share code, notes, and snippets.

@josephdpurcell
Last active November 29, 2021 18:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save josephdpurcell/c9e829f9103e76aebf697bd214ab510c to your computer and use it in GitHub Desktop.
Save josephdpurcell/c9e829f9103e76aebf697bd214ab510c to your computer and use it in GitHub Desktop.
NestJS + mongoose: how to find and set sub document values by object or array
export class MyModel extends BaseModel {
@prop({ required: false, items: MyModel })
items: MyModel[];
}
export class ModelService extends BaseService {
async findByNestedField(key: string): Promise<MyModel> {
return await this.findOneAsync(
{
items: {
$elemMatch: { key: key }
}
}
);
}
async setNestedField(id: string, key: string, nestedFieldValue: any): Promise<void> {
// TODO: this does not work!!
await this.model.updateOne(
{
_id: id,
items: {
$elemMatch: {
key: key,
},
},
},
{
$set: {
'items.$.nestedField': nestedFieldValue
},
},
);
}
}
export class MyModel extends BaseModel {
@prop({ required: false, items: MyModel })
items: Record<string, MyModel>;
}
export class ModelService extends BaseService {
async findByNestedField(key: string): Promise<MyModel> {
return await this.findOneAsync(
{
[`items.${key}`]: {
$exists: true,
},
}
);
}
async setNestedField(id: string, key: string, nestedFieldValue: any): Promise<void> {
const putObject = {};
putObject['items.' + key] = {
key: key,
nestedField: nestedFieldValue,
};
return await this.model
.findByIdAndUpdate(id, { $set: putObject })
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment