Anjil Dhamala
Anjil Dhamala

Reputation: 1622

List results based on whether they have a certain property

Here are two kind of responses when I list all the users in my db.

{
_id: "5bcf4f4d48a3067897c22344",
__v: 0
},
{
_id: "5bcf507b65f77778ab23b53f",
firstname: "major",
lastname: "general",
__v: 0
}

As you can see, there is an entry without firstname and lastname prop. At this point, I'm trying to clean up the db and remove all the ones that don't have firstname or lastname property. Here's what I have.

async deleteUsersWithoutNames() {
    const usersWithNoName = await this.userModel.find()
        .where((response: any) => response.hasOwnProperty('firstname')).equals(false);
    return usersWithNoName;
  }

This doesn't work and express screams that the path must be a string or object.

This is the userModel initialization.

  private userModel = new UserEntity().getModelForClass(UserEntity);

UserEntity class extends Typegoose by Typegoose.

How do I go on about doing this?

Upvotes: 0

Views: 28

Answers (1)

Andrei
Andrei

Reputation: 1216

now that I think about it a better way to solve your query

https://docs.mongodb.com/manual/reference/operator/query/exists/

async deleteUsersWithoutNames() {
    return await this.userModel.where({firstname: {$exists:false}})       
}

Upvotes: 1

Related Questions