2017-02-14 46 views
1

我有這條路徑用於搜索orderId的部分用戶輸入。Mongoose:如何查詢填充內的對象?

ordersAdminRouter.route('/searchorder/:term') 
    .get(function(req, res){ 
     term = req.params.term; 
     console.log(term); 
     Orders.find({orderId: new RegExp(term)}) 
      .populate({ path: 'userPurchased products.product', select: '-username -password' }) 
      .exec(function(err, orders){ 
       if (err) throw err; 
       console.log(orders); 

       res.json(orders); 
      }); 
    }); 

這裏是我的架構

var orderSchema = new Schema({ 
    orderId: { type: String }, 
    userPurchased: { type: Schema.Types.ObjectId, ref: 'users' }, 
    products: [ 
     { 
      product: { type: Schema.Types.ObjectId, ref: 'products' }, 
      size: { type: String, required: true }, 
      quantity: { type: Number, required: true }, 
      subTotal: { type: Number, required: true } 
     } 
    ], 
    totalQuantity: { type: Number }, 
    totalPrice: { type: Number }, 
    modeOfPayment: { type: String }, 
    shippingAd: { type: String }, 
    refNumber: { type: String }, 
    isDone: { type: Boolean, default: false }, 
    orderStatus: { type: String, default: 'Pending' }, 
    dateOrdered: { type: Date, default: Date.now() }, 
    fromNow: { type: String } 
}); 

現在我需要尋找內userPurchased名字和姓氏時,我填充我只得到。如何搜索它?

+0

@ThomasBormans我認爲方法是不是很好的表現明智的。我需要獲取db上的所有內容,然後每隔400ms進行一次過濾,這是我的搜索輸入實現。我的訂單數據庫非常大,因此有時需要10secs,因爲base64編碼的圖像。那麼如果沒有其他辦法,那麼我沒有選擇。 –

+0

你是絕對正確的,但問題是相同的(我認爲)。這就是我將其標記爲重複的原因。 –

回答

0

我無法理解您在'userPurchased'字段中保存的是什麼類型的信息。我假設用戶處於不同的集合中,並且您只會將用戶的用戶ID保留在用戶購買的用戶中。如果你是剛剛放置的ID,您可以搜索使用下面的查詢:

orderSchema.find({userPurchased : 'id'}) 

如果你把帶有字段的對象,沒有任何神祕感。只需使用.運營商。例如:

orderSchema.find({userPurchased.firstName : 'name'}) 

希望它可以幫助你

+0

你的第一個陳述是真實的。 userPurchased只是一個基於我的模式的ID。我正在尋找userPurchased.firstname,但這些字段只會在.populate方法之後存在。這意味着我不能使用orderSchema.find({userPurchased.firstname:'name'}),因爲userPurchased只是一個ID BEFORE .populate –

+0

我明白了,對不起,如果我的回答不是你要找的。當你說要搜索名字時,這意味着你想在第一次搜索後執行第二次搜索,對吧? –

+0

我試圖找到的是在find()上的第一條語句上進行搜索,以便減少返回文檔的大小。 –