【发布时间】:2020-02-14 10:19:56
【问题描述】:
我正在创建一个包含 mongoose、node 和 angular 的博客应用程序,其中涉及两个模型模式。一个用于博客,另一个用于类别。创建博客时,从类别模型中获取类别。理想的功能应该是,当用户点击创建博客 api 时,首先会加载一个表单以及一个下拉列表,其中通过获取请求获取现有类别列表,并且每个元素都是类别模型的文档,具有创建的唯一 id shortId、categoryName 以及 mongoose id。在下拉列表中仅获取 categoryName。现在,当用户填写表单并提交时,在节点控制器函数中,类别应该保存 categoryId 而不是 categoryName,这样我以后可以对具有相同 categoryId 的多个博客进行排序。但是在创建博客时,我的类别未定义。但是这样做时它会在控制台上获取错误:类别未定义
博客模型:
const mongoose = require('mongoose')
const Schema = mongoose.Schema;
let blogSchema = new Schema(
{
blogId: {type: String,unique: true,index: true},
title: {type: String,default: ''},
category : {type: Schema.Types.ObjectId, ref: 'Category'},
imagePath: {type: String,default: '' }})
mongoose.model('Blog', blogSchema);
类别模型:
var mongoose = require('mongoose');
const Schema = mongoose.Schema;
var CategorySchema = new Schema(
{
categoryId: {
type: String,unique: true,index: true},
categoryName: {
type: String,default: ''
}})
mongoose.model('Category', CategorySchema);
博客创建控制器功能:
let createBlog = (req, res) => {
CategoryModel.findOne({ 'categoryName': req.body.category }, (err, result) => {
if (err) { console.log('Error at finding categoryId ::', err); res.send(err) }
/** If db operation is success findOne will return either document or null, we're only projecting _id */
if (result) {
console.log('ZZZZZ'+result.categoryId)
let blogId = shortid.generate()
let newBlog = new BlogModel({
blogId: blogId,
title: req.body.title,
category: mongoose.Types.ObjectId(result.categoryId), // As result._id will be string needs to convert it to ObjectId()
imagePath: req.file.path
})
newBlog.save((err, result) => {
if (err) { console.log('Error at saving new blog ::', err); res.send(err) }
else { console.log('Successfully saved new blog'); res.send(result) }
})
} else {
console.log('No category found for ::', req.body.category)
res.send('No category found')
}
})
}
【问题讨论】:
-
似乎您将值
movies传递给Blog模型中的category字段,而不是传递有效的ObjectId(),您需要记录此请求req.body.category并检查是什么价值!! -
那么我应该如何在博客模型的类别字段中传递 ObjectId()?
-
你在
req.body.category中得到了什么你想传递给类别字段的内容? -
我要拍电影
-
如果您必须将
Movies存储为category中的字符串,则将此category : {type: Schema.Types.ObjectId, ref: 'Category'},替换为category : {type: String}