nodejs模块循环引入的问题
blog.js
const mongoose = require('mongoose')
const Schema = mongoose.Schema
const Category = require('./category')
const User = require('./user')
// 从comment.js引入Comment==========================
const Comment = require('./comment')
const blogSchema = new Schema({
category: {
type: mongoose.Schema.Types.ObjectId,
ref: Category
},
title: {
type: String,
require: true
},
desc: {
type: String,
require: true
},
content: {
type: String,
require: true
},
add_time: {
type: Date,
default: new Date()
},
author: {
type: mongoose.Schema.Types.ObjectId,
ref: User
},
view_count: {
type: Number,
default: 0
},
comment: {
type: mongoose.Schema.Types.ObjectId,
ref: Comment
}
})
module.exports = Blog = mongoose.model('blogs', blogSchema)
comment.js
const mongoose = require('mongoose')
// 从blog.js引入Blog===============================
const Blog = require('./blog')
const User = require('./user')
const commentSchema = new mongoose.Schema({
blog: {
type: mongoose.Schema.Types.ObjectId,
ref: Blog
},
content: {
type: String,
require: true
},
add_time: {
type: Date,
default: Date.now
},
author: {
type: mongoose.Schema.Types.ObjectId,
ref: User
}
})
module.exports = Comment = mongoose.model('comments', commentSchema)
报错信息:Invalid ref at path “blog”. Got {}
4 回复
放一起啊…
const Comment; process.nextTick(()=>Comment = require(’./comment’)); 两个文件都这样处理下试试
想要解决这个问题有一个很简明的方法,那就是在循环依赖的每个模块中先导出自身,然后再导入其他模块
我的思路是消除循环而不是解决导入。