Nodejs 我把论坛标签又加上去了,但是重新编辑又没了

Nodejs 我把论坛标签又加上去了,但是重新编辑又没了

如题,发布话题可以,但重新编辑话题就删掉标签了,一定是哪里不对

更改commit: https://github.com/nosqldb/nodeclub/commit/43e8b7fb62a1a70d7b04e350ae41b114d86eeeb0

测试地址 http://nosqldb.org


2 回复

根据你提供的信息,看起来你在使用 Node.js 开发一个论坛应用(例如 NodeClub),并且遇到了一个问题:当用户重新编辑话题时,之前添加的标签会被删除。这可能是由于标签数据在数据库中没有正确地更新导致的。

分析问题

首先,我们需要确认几个关键点:

  1. 数据模型:确保你的数据模型正确地保存了标签。
  2. 编辑逻辑:检查编辑话题时的逻辑,确保标签被正确地保存。
  3. 前端交互:确认前端是否正确地传递了标签数据到后端。

示例代码

假设你使用的是 MongoDB 作为数据库,并且使用 Mongoose 作为 ORM 工具。我们可以从数据模型和编辑逻辑入手来解决这个问题。

数据模型

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const TopicSchema = new Schema({
    title: String,
    content: String,
    tags: [String] // 存储标签的数组
});

module.exports = mongoose.model('Topic', TopicSchema);

编辑逻辑

假设你在后端有一个 /api/topic/:id 的路由用于处理编辑请求。你需要确保在更新话题时保留原有的标签。

const express = require('express');
const Topic = require('./models/topic'); // 引入数据模型
const router = express.Router();

router.put('/topic/:id', async (req, res) => {
    try {
        const { id } = req.params;
        const { title, content, tags } = req.body;

        // 查找现有话题
        let topic = await Topic.findById(id);

        if (!topic) {
            return res.status(404).send({ message: '话题未找到' });
        }

        // 更新话题信息,保留原有标签
        topic.title = title || topic.title;
        topic.content = content || topic.content;
        topic.tags = tags || topic.tags; // 如果没有传递新的标签,则保留原有的标签

        // 保存更新后的文档
        await topic.save();

        res.send(topic);
    } catch (error) {
        res.status(500).send({ message: error.message });
    }
});

module.exports = router;

前端交互

确保前端在编辑话题时正确地传递了标签数据。例如,使用 Axios 发送 PUT 请求:

axios.put(`/api/topic/${topicId}`, {
    title: newTitle,
    content: newContent,
    tags: newTags // 确保这里包含了新的标签
})
.then(response => {
    console.log('话题已成功更新', response.data);
})
.catch(error => {
    console.error('更新失败', error);
});

通过上述步骤,你应该能够解决重新编辑话题时标签丢失的问题。如果问题仍然存在,请检查是否有其他中间件或逻辑影响了标签的保存。


根据你的描述,问题可能是由于在保存编辑时没有正确处理标签数据。以下是一个简单的示例来说明如何处理标签数据。

示例代码

假设你有一个论坛帖子模型(Post)和一个标签模型(Tag)。在编辑帖子时,你需要确保标签数据能够正确保存。

Post 模型

const mongoose = require('mongoose');

const postSchema = new mongoose.Schema({
    title: { type: String, required: true },
    content: { type: String, required: true },
    tags: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Tag' }] // 关联标签
});

const Post = mongoose.model('Post', postSchema);

module.exports = Post;

Tag 模型

const mongoose = require('mongoose');

const tagSchema = new mongoose.Schema({
    name: { type: String, required: true, unique: true }
});

const Tag = mongoose.model('Tag', tagSchema);

module.exports = Tag;

编辑帖子逻辑

const Post = require('./models/post');
const Tag = require('./models/tag');

async function editPost(postId, updatedData) {
    const post = await Post.findById(postId);

    if (!post) {
        throw new Error('Post not found');
    }

    // 更新其他字段
    post.title = updatedData.title;
    post.content = updatedData.content;

    // 处理标签
    const tags = updatedData.tags.map(tagName => 
        Tag.findOneAndUpdate({ name: tagName }, { name: tagName }, { upsert: true, new: true })
    );

    post.tags = (await Promise.all(tags)).map(tag => tag._id);

    await post.save();
}

解释

  1. Post 模型:定义了一个 tags 字段,用于存储与帖子关联的标签对象ID。
  2. Tag 模型:定义了一个标签模型,并确保标签名称是唯一的。
  3. 编辑帖子逻辑:在更新帖子时,首先找到帖子,然后更新标题和内容。接着处理标签数据:
    • 使用 updatedData.tags 获取新的标签列表。
    • 对每个标签名称执行 findOneAndUpdate,如果标签不存在则创建它。
    • 将新标签的 _id 存储到 post.tags 中。
    • 最后保存更新后的帖子。

通过这种方式,你可以确保在编辑帖子时,标签数据能够正确地保存下来。

回到顶部