2016-02-29 43 views
0

我想從users數組中獲取指定字段的值。 類似於{_id: {$in: this.users}}。不同的是,users是一個對象數組,我想獲取此數組中每個對象的_id字段。 下面是一個代碼示例:如何獲取mongodb中的對象數組中的指定字段的值

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

而且我想寫這中間件貓鼬UserSchema:

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

但我不知道如何使用$in公司取回_company場。

任何幫助將不勝感激。謝謝。

+0

哪裏''UserSchema'的users'領域? – zangw

+0

Sory,複製粘貼後我沒有改變它。它應該是另一個Schema。 – kuba12

回答

1

請試試這個

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

好吧,據我所知,你有一個名爲users的數組,它有你的用戶對象。而你只想得到該數組的_id字段值。所以,你可以做這樣的事情:

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

現在,你有用戶的_id值,你可以用你的查詢繼續。

+0

我有一個數組,名爲companies,並且有我的公司對象。我想要的是來自陣列命名公司的_company字段。 – kuba12

+0

執行此操作:'var _companies = companies.map(function(company){return company._company});' –

+0

這將從公司數組中的每個對象返回_company字段。 –

相關問題