简体   繁体   中英

ObjectParameterError when saving to database with mongoose

I'm making a small blog until now everything works great but now that I try to add a second Schema for categories I got this error ObjectParameterError: Parameter "obj" to Document() must be an object, got . This is the part of the code that is been interested:

const blog_create_post = (req, res) => {
    const blog = new Blog(req.body);
    const category = new Category(req.body.category)
    ...
}

The first declaration work, but the second one send me the error Full error:

ObjectParameterError: Parameter "obj" to Document() must be an object, got <text>

This is req.body :

body: {
    category: 'wdawda',
    title: 'awdawd',
    snippet: 'dawdaw',
    body: 'dawdawda'
  }

Mongoose Schema:

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;

I tried this:

var things = req.body.category
const category = new Category(things);

and I don't have any error until the next line. This is the whole function:

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));
    }
}

the new error is this:

UnhandledPromiseRejectionWarning: CastError: Cast to string failed for value "{ category: 'awdawd' }" at path "category" for model "Category"

You can try this:

const category = new Category({ category: req.body.category })

This line in the blog_create_post function:

const blog_create_post = (req, res) => {
    const blog = new Blog(req.body);
    const category = new Category({ category: req.body.category });
    ...
}

I pass a object with "category" attribute instead of "category" value directly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM