【发布时间】: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