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 _id
爲order_meta
有默認值{}。如何有效填充查詢,以便它可以照顧這個測試用例?
你究竟想要做什麼?如果你想填充,你需要ObjectId,而不是Mixed。同樣空的對象沒有意義 - 它可以是null/undefined,也可以是acutal reference。 – libik
在前端我想要'order_meta'大小爲0,以防萬一,如果沒有入口但不是'null'或'undefined'。爲了處理這個測試用例,我使用了'Mixed'類型 –
這是與從數據庫導出數據有關的東西,因此您不應該將此邏輯放入模型中。 您可以重寫toJSON方法,您可以在其中使用「if」null,然後將其設置爲空對象,然後在您將其發送到前端後以這種方式進行序列化。 – libik