如何获取mongodb中对象数组中指定字段的值

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

我想从 users 数组中获取指定字段的值。 类似于 {_id: {$in: this.users}}。区别在于 users 是一个对象数组,我想得到这个数组中每个对象的 _id 字段。 这是一个代码示例:

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
})

我想为 mongoose UserSchema 编写这个中间件:

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

但我不知道如何从使用 $in 的公司检索 _company 字段。

如有任何帮助,我们将不胜感激。谢谢。

好的,据我所知,您有一个名为 users 的数组,其中包含您的用户对象。您只想从该数组中获取 _id 字段值。所以你可以这样做:

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

现在您已经有了用户的 _id 个值,您可以继续查询了。

请试试这个

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