MongoDB常见错误
生活随笔
收集整理的這篇文章主要介紹了
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常见错误的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 自动驾驶资料分享
- 下一篇: Object类型转为Map 强制转换