【问题标题】:How to loop through an array of tags ids and validate them to check if they exist in the database?如何遍历一组标签 id 并验证它们以检查它们是否存在于数据库中?
【发布时间】:2021-08-29 02:41:38
【问题描述】:

所有解释都在代码cmets中:

/* This is an node.js express app */
const express = require("express");
const Sequelize = require("sequelize").Sequelize;
const { DataTypes } = require("sequelize");
const faker = require("faker");

const app = express();

/* Using Middlewares */
app.use(express.json());

/* Creating database connection */
const sequelize = new Sequelize({
  dialect: "sqlite",
  storage: "test.sqlite",
});

/* Defining database models */
const BlogPost = sequelize.define("BlogPost", {
  title: DataTypes.STRING,
  description: DataTypes.TEXT,
});
const Tag = sequelize.define("Tag", { name: DataTypes.STRING });

/* Defining Associations (relations) */
BlogPost.belongsToMany(Tag, {
  through: "BlogPosts_Tags",
  foreignKey: "blogPostId",
});
Tag.belongsToMany(BlogPost, { through: "BlogPosts_Tags", foreignKey: "tagId" });

/* Defining Routes */
app.post("/create-blog-post", async (req, res, next) => {
  const title = req.body.title;
  const description = req.body.description;
  const tagsIds = req.body.tagsIds;

  /*
  Here i want to take the tagsIds array which contains the tags ids of the tags i chose for my blog
  post and check if each tag exists in the database using:
  
  const tagById = await Tag.findByPk(tagId);
  
  If the tagById is the tag then the tag exists and if its null then the tag does not exist in the
  database. I want to loop through all the Ids in the tagsIds array and do that check to all of them.

  How can i do that ? I tried the following code but it didnt work.
  */
  let validationResult;
  tagsIds.forEach(async (tagId) => {
    const tagById = await Tag.findByPk(tagId);
    if (tagById === null) {
      console.log("The tag with id of " + tagId + " does not exist");
      return (validationResult = null);
    }
  });
  if (validationResult === null) {
    res.json("Invalid one or more tags");
  } else {
    res.json("Validation Succeeded!");
  }

  /* I always get the Validation Succeeded! response, i think the problem is in the async
  await mechanism, any solutions ? */

  /* Then after validation i want to create a blog post with those tags i chose and validated
  related to the blog post and register the relation in the junction BlogPosts_Tags table */
});

/* Self executing anonymous function */
(async () => {
  try {
    /* Syncing Database */
    await sequelize.sync();
    /* Creating some fake tags */
    let fakeTags = [];
    for (let i = 0; i < 5; i++) {
      fakeTags.push({ name: faker.lorem.word() });
    }
    Tag.bulkCreate(fakeTags);
    /* Start Listening if syncing succeeded */
    app.listen("3111");
  } catch (err) {
    console.log(err);
  }
})();

所有解释都在代码 cmets 中,这是绕过添加更多详细信息错误的垃圾邮件。所有解释都在代码 cmets 中,这是绕过添加更多详细信息错误的垃圾邮件。所有解释都在代码 cmets 中,这是绕过添加更多详细信息错误的垃圾邮件。所有解释都在代码 cmets 中,这是绕过添加更多详细信息错误的垃圾邮件。所有解释都在代码 cmets 中,这是绕过添加更多详细信息错误的垃圾邮件。所有解释都在代码 cmets 中,这是绕过添加更多详细信息错误的垃圾邮件。

【问题讨论】:

    标签: node.js express sequelize.js


    【解决方案1】:

    我是这样解决的:

    let tags = [];
      /* Validating all the tags in the tagsIds array */
      for (const tagId of tagsIds) {
        const tagById = await Tag.findByPk(tagId);
        tags.push(tagById);
      }
    
      /* check if there is any null values in the tags */
      if (tags.includes(null)) {
        res.json("One or more tags are invalid!");
      } else {
        /* Create the blog post with the title and description */
        const blogPost = await BlogPost.create({
          title: title,
          description: description,
        });
        /* Then associate the tags to the blog post */
        const result = await blogPost.addTags(tags);
        res.json(result);
      }
    

    【讨论】:

    • 如果您有更好的解决方案,可以一步完成创建和添加2个步骤,请发布。
    猜你喜欢
    • 1970-01-01
    • 2015-11-20
    • 1970-01-01
    • 2012-06-13
    • 2018-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-10
    相关资源
    最近更新 更多