日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

MongoDB常见错误

發布時間:2023/12/29 编程问答 21 豆豆
生活随笔 收集整理的這篇文章主要介紹了 MongoDB常见错误 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

1、Schema hasn't been registered for model "User":在對兩張表Article和User進行關聯后調用author時報錯

const mongoose = require('mongoose');mongoose.connect('mongodb://localhost/playground', { useNewUrlParser: true, useUnifiedTopology: true }).then(() => {console.log('數據庫連接成功'); }).catch(err => {console.log('數據庫連接失敗'); }); const articleTable = mongoose.model('Article', new mongoose.Schema({ title: String, author: { type: mongoose.Schema.Types.ObjectId, ref: 'User' } })); articleTable.find().populate('author').then(res => {console.log(res); })

解決辦法:在查詢前獲取User表

const mongoose = require('mongoose');mongoose.connect('mongodb://localhost/playground', { useNewUrlParser: true, useUnifiedTopology: true }).then(() => {console.log('數據庫連接成功'); }).catch(err => {console.log('數據庫連接失敗'); });const userTable = mongoose.model('User', new mongoose.Schema({ name: String }));const articleTable = mongoose.model('Article', new mongoose.Schema({ title: String, author: { type: mongoose.Schema.Types.ObjectId, ref: 'User' } }));articleTable.find().populate('author').then(res => {console.log(res); })

2、通過mongoose進行數據驗證時default屬性失效,原因是表單在為空時會提交空字符串'',而空字符串不會觸發default,只有當屬性不存在時才會觸發。解決方法:1、使用required屬性強制要求Input不能為空,不使用default來進行默認值2、獲取數據后判斷是否為空字符串,如果是的話就賦值為空,觸發default賦值。

3、通過populate查詢返回的數據在渲染模板的時候報錯:Maximum call stack size exceeded。

let arts = await Article.find().populate('author'); res.render('admin/article', {articles: arts})

解決方案:1、在查詢鏈后面調用lean讓其返回普通對象而不是mongoose對象

let arts = await Article.find().populate('author').lean();

2、使用JSON方法格式化對象

JSON.stringify(arts);JSON.parse(arts);

?

總結

以上是生活随笔為你收集整理的MongoDB常见错误的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。