0

我在mongoose-TweetComment模型中有 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

有谁知道出了什么问题?我理解错了吗?

4

0 回答 0