我在mongoose
-Tweet
和Comment
模型中有 2 个模式。
架构Tweet
:
const mongoose = require('mongoose')
const { Schema } = mongoose
const tweetSchema = new Schema(
{
author: {
type: String,
required: true
},
title : {
type: String,
required: true
},
body:{
type: String,
required: true
},
reactions: {
likes: {
type: Number,
default : 0
},
dislikes: {
type: Number,
default : 0
}
},
comments: [{
type: Schema.Types.ObjectId,
ref: 'Comment'
}]
},
{
timestamps: true
}
)
const Tweet = mongoose.model('Tweet', tweetSchema)
module.exports = Tweet
架构Comment
:
const mongoose = require('mongoose')
const Tweet = require('./tweet')
const { Schema } = mongoose
const commentSchema = new Schema(
{
author: {
type: String,
required: true
},
body: {
type: String,
required: true
},
reactions: {
likes: {
type: Number,
default : 0
},
dislikes: {
type: Number,
default : 0
}
},
tweet: {
type: Schema.Types.ObjectId,
ref: 'Tweet',
required: true
}
},
{
timestamps: true
}
)
commentSchema.post('save', async doc => {
console.log('hello world')
console.log(doc)
try {
await Tweet.updateOne(
{
_id: doc.tweet
},
{
$push: {
comments : doc._id
}
}
)
} catch(e) {
console.log(e)
}
})
const Comment = mongoose.model('Comment', commentSchema)
module.exports = Comment
在POST
路线上,我有:
app.post('/comments', async (req, res) => {
try {
const { author, tweetId, body } = req.body
await Comment.create({
body,
author,
tweet: tweetId
})
res.redirect(`/tweets/${tweetId}`)
} catch(e) {
res.status(400).send({
name: e.name,
message: e.message
})
}
})
在创建评论时,我想使用post
钩子中间件来更新文档comments
中的字段。tweet
根据mongoose
的文档,Model.create()
触发save()
中间件。这是正确的,因为打印了“hello world”。doc
也在打印新创建的comment
文档。
但是,我收到一条错误消息:
TypeError: Tweet.updateOne is not a function
.
.
.
(node:9367) Warning: Accessing non-existent property 'updateOne' of module exports inside circular dependency
有谁知道出了什么问题?我理解错了吗?