我有這 2 個貓鼬模式,第一個嵌入在第二個中
const mongoose = require("mongoose");
const CommentSchema = mongoose.Schema({
user: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User',
required: true
},
text: {
type: String,
minLength: 3,
maxlength: 500,
required: true
},
}, {timestamps: true} );
const PictureSchema = mongoose.Schema({
user: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User',
required: true
},
title: {
type: String,
minLength: 3,
maxlength: 80,
required: true
},
comments: [CommentSchema]
}, {timestamps: true} );
module.exports = mongoose.models.Picture || mongoose.model('Picture', PictureSchema);
兩種模式都在同一個檔案中。請注意,這兩個檔案都參考了另一個名為 User 的 Schema。保存時出現錯誤:
const comment = new Comment({
user: user,
text: description
});
const picture = new Picture({
user: user,
title: title
});
picture.comments.push(comment);
await picture.save();
user 是來自另一個模式的用戶物件,我相信添加它正在作業的 comments 陣列和以前一樣好。
我收到的錯誤是ReferenceError: Comment is not defined
在我看來,因為我包括這樣的圖片
const Picture = require('../model/Picture');
它找不到評論,但我嘗試將它們放在 2 個單獨的檔案中,但仍然無法正常作業。
我究竟做錯了什么?
uj5u.com熱心網友回復:
在我看來,您只有模塊匯出有問題。要從Comment外部檔案訪問,您需要將其匯出。
在模式定義檔案的末尾使用:
module.exports.Picture = mongoose.models.Picture || mongoose.model('Picture', PictureSchema);
module.exports.Comment = mongoose.models.Comment || mongoose.model('Comment', CommentSchema);
在您使用模型的檔案中使用:
const { Picture, Comment } = require('../model/Picture');
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/459381.html
下一篇:嘗試讀取mongoDB檔案屬性
