kuba12
kuba12

Reputation: 265

How to get value of specified field in an array of objects in mongodb

I want to get values of specified field from the users array. Something like {_id: {$in: this.users}}. The difference is that users is an array of objects and I want to get the _id field of each object in this array. Here's a code sample:

var UserSchema = new Schema({
    username: {type: String, required: true, unique: true},
    password: {type: String, required: true,},
    email: {type: String, required: true, unique: true},
    role: {type: String, enum: ['user'], required: true},
    name: String,
    phoneNumber: Number,
    companies: [{
        _company: {type: Schema.ObjectId, ref: 'Company'},
        points: Number
    }],
    points: Number,
    created_at: Date,
    updated_at: Date
})

And I want write this middleware for mongoose UserSchema:

UserSchema.pre('remove', function(next) {
    this.model('Company').update(
        {_id: {$in: ??????????????????}},
        {$pull: {users: this._id}},
        next()
    )
})

But I don't know how to retrieve _company field from companies using $in.

Any help will be appreciated. Thanks.

Upvotes: 1

Views: 1536

Answers (2)

zangw
zangw

Reputation: 48356

Please try this

UserSchema.pre('remove', function(next) {
    var ids = this.companies.map(function(o) {return o._company;});
    this.model('Company').update(
        {_id: {$in: ids}},
    //...

Upvotes: 1

SiddAjmera
SiddAjmera

Reputation: 39432

Ok so as far as I understood, you have an array named users, that has your User Objects. And you want to get just the _id field values from that array. So you can do something like this :

var ids = users.map(function(user){ return user._id });

Now that you have the _id values of the users, you can go ahead with your query.

Upvotes: 1

Related Questions