1

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.

2
  • Where is the users field of UserSchema? Commented Feb 29, 2016 at 14:14
  • Sory, I didn't change it after Copy-Paste. It should be another Schema. Commented Feb 29, 2016 at 14:34

2 Answers 2

1

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}},
    //...
Sign up to request clarification or add additional context in comments.

Comments

1

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.

3 Comments

I have an array, named companies and there are my companies objects. What I want to get is _company field from array named companies.
Do this : var _companies = companies.map(function(company){ return company._company });
This will return the _company field from each object in your companies array.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.