【问题标题】:How to get value of specified field in an array of objects in mongodb如何在mongodb的对象数组中获取指定字段的值
【发布时间】:2016-06-12 13:38:07
【问题描述】:

我想从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 字段。

任何帮助将不胜感激。谢谢。

【问题讨论】:

  • UserSchemausers 字段在哪里?
  • 抱歉,复制粘贴后我没有更改它。它应该是另一个 Schema。

标签: arrays node.js mongodb mongoose mongoose-schema


【解决方案1】:

请试试这个

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

【讨论】:

    【解决方案2】:

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

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

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

    【讨论】:

    • 我有一个数组,命名为公司,还有我的公司对象。我想得到的是数组命名公司中的 _company 字段。
    • 这样做:var _companies = companies.map(function(company){ return company._company });
    • 这将返回公司数组中每个对象的 _company 字段。
    猜你喜欢
    • 2019-08-12
    • 2018-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-04
    • 2020-07-04
    • 2021-11-09
    • 1970-01-01
    相关资源
    最近更新 更多