node.js - 函数在nodejs中没有返回任何东西
问题描述
我正在创建一个网络应用程序的后端,其中存储了不同的帖子并且还存储了它们的类别。由于每个类别都有自己的属性(如描述、颜色等),因此我创建了一个新的类别架构并将类别引用存储在文章中。这是我的发帖路线:
Code_1
Code_2
// CREATE ROUTE : adding New Article
app.post("/addnew", upload.single('image'), function(req,res){
//get data from form and add to news array
var title = req.body.title;
var image = req.body.image
if (req.file){
var imgURL = req.file.path;
}
var description = req.body.description;
var category = req.body.category;
var tag = req.body.tag;
// Handling the category entered by user
function checkCategory(name , color, totalArticles, desc){Category.find({name: category}, (err, foundCategory) => {
if(err){
console.log(err)
} else {
console.log("found category in starting of checkCategory function : " , foundCategory)
if (foundCategory[0]){
console.log("Category" + foundCategory + "already exists...")
return foundCategory
} else {
// var name = req.body.name
// var color = req.body.color
// var totalArticles = req.body.totalArticles
// var desc = req.body.desc
var category = {name: name , color : color , totalArticles: totalArticles || 0 , desc : desc }
Category.create(category, (err, newCategory) => {
if (err){
console.log(err)
} else {
console.log("New category Created : " , newCategory)
// category = newCategory
return newCategory
}
})
}
}
})
}
console.log("??????????????? category returned", category)
var nyaArticle= {title: title, imgURL: imgURL, description: description};
// create a new Article and save to db
Article.create(nyaArticle,function(err,newArticle){
if(err){
console.log(err);
} else {
// redirect back to main page
console.log("new article created")
console.log(newArticle)
category = checkCategory(req.body.name, req.body.color, req.body.totalArticles, req.body.desc)
console.log("checkCategory Returned :::::" , category)
newArticle.category.push(category)
newArticle.save()
res.redirect("/");
}
})
函数 checkCategory 检查类别是否已经存在,否则它将创建一个新类别。但是根据这些日志,我的函数没有返回创建的类别,但是该类别已在 DB 中成功创建,也可以在Logs中看到
Articles App has started on port 3000
DB Connected...: cluster0-shard-00-00-ktzf1.mongodb.net
??????????????? category returned undefined
new article created
{
category: [],
hits: 0,
tag: [],
comments: [],
_id: 60be0fe92a8b88a8fcea71dc,
title: 'TESTING',
description: 'TESTING',
created: 2021-06-07T12:24:09.563Z,
__v: 0
}
checkCategory Returned ::::: undefined
found category in starting of checkCategory function : []
New category Created : {
totalArticles: 444,
_id: 60be0fea2a8b88a8fcea71dd,
name: 'TESTING',
color: 'RED ALERT',
desc: 'THiS TESTING',
__v: 0
}
由于这个 null 被存储在我的 DB类别中
我是使用正确的方法还是应该遵循其他方法,非常欢迎任何帮助。
categorySchema 如下所示:
var categorySchema = new mongoose.Schema({ name: String, color: String, totalArticles: { type:Number, default: 0 }, desc : String });
文章架构:
var newSchema = new mongoose.Schema({
title: String,
imgURL: String, //{type: String, default: "https://source.unsplash.com/1600x1080/?news"},
description: String,
// category: String,
category: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "Category"
}
],
hits : {
type: Number ,
default : 0
},
tag: [
{type: String}
],
created: {type: Date, default: Date.now},
comments: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "Comment"
}
]
});
解决方案
您正在从您的返回的回调函数var category
内部进行分配,并且该 var 仅在该回调中可用。
此外,您的代码还有其他几个问题,例如永远不会返回任何内容。(应该是)。
一般来说,使用 , 会更好(如果你愿意,可以加上 a ):checkCategory
Category.find({name: category})
{name:name}
async\await
try\catch
async function checkCategory(name, color, totalArticles, desc) {
try {
let category = await Category.findOne({ name });
if (category) {
console.log(`Category ${category.name} already exists...`);
return category;
}
else {
let newCategory = await Category.create({ name: name, color: color, totalArticles: totalArticles || 0, desc: desc });
console.log("New category Created : ", newCategory);
return newCategory;
}
} catch (error) {
console.log(err)
}
}
在您的路由器功能中:
app.post("/addnew", upload.single('image'), async function(req,res){
let {name, color, totalArticles, desc} = req.body;
let category = await checkCategory(name, color, totalArticles, desc);
let newArticle = await Article.create({ title: title, imgURL: imgURL, description: description, category: [category] });
res.redirect("/");
}
推荐阅读
- roku - Click button not fire a click Event and how to navigate another panel in ROKU
- r - 在数据框中按组对行进行排序、排序或排名
- xml - Remove tags from XML in PowerShell
- selenium-webdriver - 如何使用 selenium 网格从不同的机器调用并行浏览器?
- java - WildFly 15+ 无法启动持久性单元
- keycloak - 如何获取自定义用户存储提供程序的角色
- typescript - .map 文件输出的 tsc 编译器选项?
- regex - 如何仅使用纯 bash 提取 json 值?
- graphql - 大量查询情况下的 GraphQL 部署模型
- css - angular css/scss中app-root{}和app-root * {}有什么区别