我想將 shopid 和電子郵件合并并保存在名為組合的新欄位中。應該如何撰寫它的模式,以便它自動保存在資料庫中
shopId: { type: String, required: true },
id: { type: String, required: true },
email: { type: String, required: true },
firstname: { type: String, required: true },
lastname: { type: String, required: true },
_shopId: { type: mongooose.Schema.Types.ObjectId, ref: 'Shop', required: true },
combined: shopid email
})
uj5u.com熱心網友回復:
mongodb 不能強制它combined永遠是shopId email;你總是可以去后的,其實和update該combined領域的東西。我建議既節省一點空間,又將邏輯移到 agg 管道中,例如
db.foo.aggregate([
{$addFields: {combined: {$concat: [ "$shopId", "$email" ]} }}
]);
或者為了更好的清晰度
db.foo.aggregate([
{$addFields: {combined: {$concat: [ "$shopId", "-", "$email" ]} }}
]);
uj5u.com熱心網友回復:
您無法從架構中自動執行此操作。如果你想要那個“組合”欄位,你需要將它定義為一個物件或一個字串(如果你正在考慮像這樣的字串${email}${id}):
shopId: { type: String, required: true },
id: { type: String, required: true },
email: { type: String, required: true },
firstname: { type: String, required: true },
lastname: { type: String, required: true },
_shopId: { type: mongooose.Schema.Types.ObjectId, ref: 'Shop', required: true },
// In case you need a separation of your fields
combined: {
email: {
type: String,
required: true
},
shopId:{
type: String,
required: true
}
}
//In case you need that one combined string
combined: {
type String,
required: true
}
然后在保存該檔案時在邏輯中添加“組合”欄位。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/393897.html
