5
我有以下文件:使用req.body通過Mongoose更新和/或添加數組元素屬性?
{
"_id" : ObjectId("503b83dfad79cc8d26000004"),
"pdfs" : [
{
"title" : "Test document",
"pdf_id" : ObjectId("504f6793ce351a595d000004"),
"created_at" : ISODate("2012-09-11T16:32:19.276Z")
},
{
"title" : "Some other doc",
"pdf_id" : ObjectId("502bf124b4642341230003f0"),
"created_at" : ISODate("2012-09-11T11:34:19.276Z")
}
]
}
現在,在經由req.body
傳入形式,我有2個字段:title
和description
。
我想更新title
並插入description
爲指定的pdf_id,我該怎麼做?
所以在最後,我的文檔將現在的樣子:
{
"_id" : ObjectId("503b83dfad79cc8d26000004"),
"pdfs" : [
{
"title" : "This is an UPDATED title",
"description" : "It has an ALL NEW description",
"pdf_id" : ObjectId("504f6793ce351a595d000004"),
"created_at" : ISODate("2012-09-11T16:32:19.276Z")
},
{
"title" : "Some other doc",
"pdf_id" : ObjectId("502bf124b4642341230003f0"),
"created_at" : ISODate("2012-09-11T11:34:19.276Z")
}
]
}
只是要清楚,我真的只是尋找貓鼬update
語法。
在'$ set',有沒有什麼辦法來動態分配這些屬性呢?用戶可能不提供一些,我寧願不必明確指定它們。 – k00k
當然,你只需要編程建立'$ set'對象,然後把這個對象作爲第二個參數傳遞給'update'調用。有點像在這個其他問題:http://stackoverflow.com/questions/12184626/nodejs-mongo-insert-into-subdocument-dynamic-fieldname/12185214#12185214 – JohnnyHK
很酷,謝謝。有些東西讓我感到沮喪,這可能會幫助其他人:當我剛剛將我的數組設置爲混合'[]'時,它不會更新。我不得不構建數組的模式,並確保您嘗試更新的數組元素的_id在模式中被指定爲「type:Schema.Types.ObjectId」。 – k00k