2017-08-24 50 views
2

我的架構如下圖所示:如下圖所示貓鼬是不是能填充參考編號用默認值的空對象

const order = new Schema({ 
    order_status: Number, 
    foodtruck_id: { type: Schema.Types.ObjectId, ref: 'foodtruck' }, 
    customer_id: { type: Schema.Types.ObjectId, ref: 'user' }, 
    items: [{ type: Schema.Types.ObjectId, ref: 'items' }], 
    user_type: Boolean, 
    order_time: Date, 
    order_rating: { type: Number, default: 5.0 }, 
    order_issue_comments: String, 
    order_special_instruction: String, 
    order_total: Number, 
    order_location: String, 
    order_coupon_code: String, 
    payment_id: { type: Schema.Types.ObjectId, ref: 'payment' }, 
    order_meta: { type: Schema.Types.Mixed, ref: 'order_sub_info', default: {} } 
}, { versionKey: false }, { minimize: false }); 

我的查詢:

order.find({ 
     'foodtruck_id': foodtruck_id.trim() 
    }).populate('customer_id', { 
     '_id': 1, 
     'user_name': 1, 
     'email_id': 1, 
     'ph_no': 1, 
     'login_type': 1 
    }).populate('items'). 
    populate('order_meta', 'order_otp').exec((err, orderList) => { 
     if (err) res.json({ 
      status: '500', 
      message: err 
     }); 
     else { 
      console.log("called"); 
      res.json({ 
       status: '200', 
       message: 'Order list', 
       data: orderList 
      }); 
     } 
    }); 

對於此查詢,它是給我Cast to ObjectId failed for value at path _idorder_meta有默認值{}。如何有效填充查詢,以便它可以照顧這個測試用例?

+0

你究竟想要做什麼?如果你想填充,你需要ObjectId,而不是Mixed。同樣空的對象沒有意義 - 它可以是null/undefined,也可以是acutal reference。 – libik

+0

在前端我想要'order_meta'大小爲0,以防萬一,如果沒有入口但不是'null'或'undefined'。爲了處理這個測試用例,我使用了'Mixed'類型 –

+0

這是與從數據庫導出數據有關的東西,因此您不應該將此邏輯放入模型中。 您可以重寫toJSON方法,您可以在其中使用「if」null,然後將其設置爲空對象,然後在您將其發送到前端後以這種方式進行序列化。 – libik

回答

1

將空對象放在需要引用ID的地方不是個好主意。兩者 - 對於填充問題和常識(如果它是具有引用的字段,它應該是空/未定義或引用自身)。

通常情況下,您希望在某個端點轉換數據,但不應該干擾數據庫或應用程序的業務邏輯。

您可以定義爲應該用於您的模型的JSON方法。在你的情況下

const order = new Schema({ 
    order_status: Number, 
    foodtruck_id: { type: Schema.Types.ObjectId, ref: 'foodtruck' }, 
    customer_id: { type: Schema.Types.ObjectId, ref: 'user' }, 
    items: [{ type: Schema.Types.ObjectId, ref: 'items' }], 
    user_type: Boolean, 
    order_time: Date, 
    order_rating: { type: Number, default: 5.0 }, 
    order_issue_comments: String, 
    order_special_instruction: String, 
    order_total: Number, 
    order_location: String, 
    order_coupon_code: String, 
    payment_id: { type: Schema.Types.ObjectId, ref: 'payment' }, 
    order_meta: { type: Schema.Types.ObjectId, ref: 'order_sub_info'} 
}, { versionKey: false }, { minimize: false }); 

order.options.toJSON = { 
     transform(zipRequestDocument, ret, options) { // eslint-disable-line no-unused-vars 
      if (!ret.order_meta){ 
       ret.order_meta = {}; 
      } 
     }, 
    };