我正在嘗試使用 updateMany 將此新欄位添加到我的集合中的所有檔案中。我只是找不到正確的方法來做到這一點。我的欄位“sits”需要一組物件。該物件未在架構中定義。但是,它目前有 3 個欄位:sitNumber、isAvailable、isSuspended。我可以很好地插入具有這種結構的檔案。我想將欄位 price : 0 添加到所有現有檔案中。
這是集合中的示例檔案
{
flightName : 65ywdbs
sits: [
{sitNumber : 1, isAvailable: true isSuspended: false} //Want to add a price field here.
]
//etc etc
}
我的 SCHEMA 如下所示:
//models/Flight.js
const mongoose = require('mongoose')
const Schema = mongoose.Schema
const flightSchema = new Schema({
flightName :{ type : String, required :true},
sits : {type : Array,
required : true},
origin : {type: String, required : true},
destination : {type : String, required: true},
departure : {type : Date, required : true},
arrival : {type : Date, required : true}
})
module.exports = mongoose.model('Flight', flightSchema)
這是我用來將欄位 price 添加到位于集合的每個檔案中的陣列中的每個物件的查詢:
//Controllers/dashboard.js
addPrice : async(req, res) =>{
try {
const query = await Flight.updateMany({}, {$set : {'sits.price':100}} )
console.log(query)
} catch (error) {
console.log(error)
}
}
這對我來說很有意義,但它是不正確的。任何幫助將不勝感激。
uj5u.com熱心網友回復:
您可以使用$[]所有位置運算子來執行類似的操作。
您的問題類似于更新陣列中所有檔案的示例:
$[]位置運算子有助于更新包含嵌入檔案的陣列。要訪問嵌入檔案中的欄位,請在運算子中使用點符號$[]。db.collection.updateOne( { <query selector> }, { <update operator>: { "array.$[].field" : value } } )
因此,在您的情況下,您的更新將如下所示:
const query = await Flight.updateMany({}, { $set : { 'sits.$[].price': 100 }})
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/491362.html
