我一直在做一个小型博客,直到现在一切正常,但是现在我尝试为类别添加第二个模式,但出现了错误ObjectParameterError: Parameter "obj" to Document() must be an object, got
。
这是代码中感兴趣的部分:
const blog_create_post = (req, res) => {
const blog = new Blog(req.body);
const category = new Category(req.body.category)
...
}
第一个声明起作用,但是第二个向我发送错误 完整错误:
ObjectParameterError: Parameter "obj" to Document() must be an object, got <text>
这是req.body
:
body: {
category: 'wdawda',
title: 'awdawd',
snippet: 'dawdaw',
body: 'dawdawda'
}
猫鼬模式:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const categorySchema = new Schema({
category: {
type: String,
required: true
}
});
const Category = mongoose.model('Category', categorySchema);
module.exports = Category;
我尝试过:
var things = req.body.category
const category = new Category(things);
在下一行之前,我没有任何错误。这是整个功能:
const blog_create_post = (req, res) => {
const blog = new Blog(req.body);
var things = { category: req.body.category };
const category = new Category(things);
if (!Category.exists({ category: things })) {
console.log('category not exist');
category.save()
.then((result) => {
blog.save()
.then((result) => {
res.redirect('/blogs');
})
.catch((err) => console.log(err));
})
.catch((err) => res.send(err));
} else {
console.log('category exist');
blog.save()
.then((result) => {
res.redirect('/blogs');
})
.catch((err) => console.log(err));
}
}
新错误是这样的:
UnhandledPromiseRejectionWarning: CastError: Cast to string failed for value "{ category: 'awdawd' }" at path "category" for model "Category"
答案 0 :(得分:0)
您可以尝试以下方法:
This site can’t provide a secure connection 127.0.0.1 sent an invalid response.
blog_create_post函数中的这一行:
const category = new Category({ category: req.body.category })
我直接传递具有“类别”属性而不是“类别”值的对象。