[英]Mongoose Trouble Adding Subdocs to Array
我希望推送到 mongoose 中我的用戶架構上的數組。我正在關注貓鼬的將子文檔添加到 Arrays 文檔,但在 user.notes 上不斷出現錯誤。 推送(新筆記本)
類型錯誤:無法讀取未定義的屬性(讀取“推送”)
這是我的設置:
const User = require('../models/userModel')
const addNotebook = async (req, res) => {
...
const user = User.findOne({ userId })
const newNotebook = { userId: userId, notebookId: notebookId, title: title, numNotes: 0 }
user.notebooks.push(newNotebook)
}
任何幫助將非常感激。
更新 -
這是解決方案:
const User = require('../models/userModel')
const addNotebook = async (req, res) => {
...
const user = User.findOne({ userId })
if (!user) return
const newNotebook = { userId: userId, notebookId: notebookId, title: title, numNotes: 0 }
user.notebooks = user.notebooks || []; // returns user.notebooks if defined else empty array
user.notebooks.push(newNotebook)
await user.save()
}
非常感謝Mandeep向我展示了 .user 條件和 .save() 方法。 特別感謝Sardar帶來 user.notebooks = user.notebooks || 【解光】。
免責聲明:在觀看有關 MongoDB 反模式的視頻后,我了解到在單個文檔下嵌套無限數據可能會出現問題,因為每個 MongoDB 文檔被限制為 16mb。 相對於將數據保存在相應的 collections 中,它也被認為是低效的。將子文檔添加到 arrays 時要小心。
它會是這樣的:
const addNotebook = async(req, res) => { const user = await User.find({ userId }).limit(1).exec() if (:user) return const newNotebook = { userId, userId: notebookId, notebookId: title, title: numNotes. 0 } user.notebooks.push(newNotebook) await user.save() }
這可能是因為默認情況下您的 userModel/schema 未定義“notebooks”
您可以通過兩種方法解決此問題
const User = require('../models/userModel') const addNotebook = async(req, res) => {... const user = User.find({ userId }) const newNotebook = { userId: userId, notebookId: notebookId, title: title, numNotes: 0 } user.notebooks = user.notebooks || []; // returns user.notebooks if defined else empty array user.notebooks.push(newNotebook) }
推薦或者您可以像這樣在您的 userModel 中為筆記本設置默認值(可能不會更新您現有的用戶文檔) 如何在模式 mongoose 中設置默認值?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.