0

I'm getting pretty confused over the following error, as it seems pretty the same to me.

Running a Mongoose Seed, I have the following model:

User Model

const mongoose = require("mongoose")
const Schema = mongoose.Schema

const userSchema = new Schema({
    firstName: String,
    lastName: String,
    title: String,
    email: String,
    password: String,
    phone: String,
    profilePicture: String,
    profileDescription: String
}, {
    timestamps: true
})

const User = mongoose.model("User", userSchema)

module.exports = User

CV Model

const mongoose = require("mongoose")
const Schema = mongoose.Schema

const cvSchema = new Schema({
    name: String,
    user: {
        type: Schema.Types.ObjectId,
        ref: 'User'
    },
    userInfo: {
        firstName: String,
        lastName: String,
        title: String,
        email: String,
        password: String,
        phone: String,
        profilePicture: String,
        profileDescription: [{}]


    },
    employment: [{
        title: String,
        employer: String,
        start: String,
        end: String,
        city: String,
        description: String,
    }],
    education: [{
        degree: String,
        school: String,
        start: String,
        end: String,
        city: String,
        description: String,
    }],
    skills: [{
        skill: String,
        level: Number,
    }],
    links: [{
        label: String,
        link: String,
    }],
}, {
    timestamps: true,
})

const CV = mongoose.model("CV", cvSchema)

module.exports = CV

Description Model

const mongoose = require("mongoose")
const Schema = mongoose.Schema

const descriptionSchema = new Schema({ description: [{}] })

const Description = mongoose.model("descriptionSchema", descriptionSchema)

module.exports = Description

And Seed

require('dotenv').config()

const mongoose = require('mongoose')
const User = require('../models/user.model')
const CV = require('../models/cv.model')
const Template = require('../models/template.model')
const Description = require('../models/description.model')

mongoose.connect(`mongodb://localhost/${process.env.LOCALDB}`, { useNewUrlParser: true, useUnifiedTopology: true })


const bcrypt = require("bcrypt")
const bcryptSalt = 10
const salt = bcrypt.genSaltSync(bcryptSalt)


const exampleDescription = [
    {
        "type": "paragraph",
        "children":
         [
                     {"text": "This is editable "},
                     {"text": "rich","bold": true},
                     {"text": " text, "},
                     {"text": "much", "italic": true},
                     {"text": " better than a normal text !"}
         ]
    },
    { 
       "type": "paragraph",
       "children":
            [
                {"text": "Since it's rich text, you can do "},
                {"text": "thing", "bold": true},
                {"text": "s like turn a selection of text "},
                {"text": "bold", "bold": true},
            ]
    },
    {
        "type": "paragraph", 
        "children":
            [{"text": "Try it out for yourself!sdjfgndfjgkdfsgjkldsfmg" }]
    },
    {
        "type": "paragraph",
        "children": [{ "text": "" }]
    },
    {
        "type": "bulleted-list",
        "children":
            [
                { "type": "list-item", "children": [{ "text": "dfsgsdfgsdfg" }] },
                { "type": "list-item", "children": [{ "text": "dsfgsdfgsdfgjjj"}]},
                { "type": "list-item", "children": [{ "text": "dfsgsdfgdfsg"}]},
                { "type": "list-item", "children": [{ "text": "dsfg" }] },
                { "type": "list-item", "children": [{ "text": "dsfgsdfg" }]},
                { "type": "list-item", "children": [{ "text": "sdfgsdfg" }]},
                { "type": "list-item", "children": [{ "text": "dsfgsdg" }]},
                { "type": "list-item", "children": [{ "text": "" }] },
                { "type": "list-item", "children": [{ "text": "" }] }]},
                { "type": "paragraph", "children": [{ "text": "sdfgsdfgsdfgsdfg" }] },
                { "type": "paragraph", "children": [{ "text": "dfgdfsg" }] },
                { "type": "paragraph", "children": [{ "text": "" }] }
]

const users = [
    {
        firstName: "Example 1",
        lastName: "Last Name 1",
        title: "Student",
        email: "[email protected]",
        password: bcrypt.hashSync('pass1', salt),
        phone: "123456789",
        profilePicture: "https://qph.fs.quoracdn.net/main-qimg-134e3bf89fff27bf56bdbd04e7dbaedf.webp",
        profileDescription: exampleDescription,
        //profileDescription: { description: exampleDescription },
    },
    {
        firstName: "Demo 1",
        lastName: "Demo 2",
        title: "Yoga Instructor",
        email: "[email protected]",
        password: bcrypt.hashSync('pass2', salt),
        phone: "987654321",
        profilePicture: "https://www.google.com/url?sa=i&url=http%3A%2F%2Fwww.nelsonirrigation.com%2Fmedia%2Fpeople%2F%3FC%3DD%3BO%3DD&psig=AOvVaw2UHc769pta1clyVHKolHF6&ust=1589280988466000&source=images&cd=vfe&ved=0CAIQjRxqFwoTCIj2zZvTq-kCFQAAAAAdAAAAABAi",
        profileDescription: exampleDescription
        //profileDescription: { description: exampleDescription }

    },
]

const cvs = []

const createCVs = (user) => {

    cvs.push(
        {
            name: 'Apollo',
            employment: employment,
            education: education,
            skills: skills,
            links: links,
            userInfo: {
                firstName: user.firstName,
                lastName: user.lastName,
                title: user.title,
                email: user.email,
                phone: user.phone,
                profilePicture: user.profilePicture,
                profileDescription: user.profileDescription
            },
            user: user.id
        },
        {
            name: "Poseidon",
            employment: employment,
            education: education,
            skills: skills,
            links: links,
            userInfo: {
                firstName: user.firstName,
                lastName: user.lastName,
                title: user.title,
                email: user.email,
                phone: user.phone,
                profilePicture: user.profilePicture,
                profileDescription: user.profileDescription
            },
            user: user.id
        },
        {
            name: "Hermes",
            employment: employment,
            education: education,
            skills: skills,
            links: links,
            userInfo: {
                firstName: user.firstName,
                lastName: user.lastName,
                title: user.title,
                email: user.email,
                phone: user.phone,
                profilePicture: user.profilePicture,
                profileDescription: user.profileDescription
            },
            user: user.id
        }
    )
}

const employment = [
    {
        title: "Marketing Consultant",
        employer: "Neointec",
        start: "Jan-2019",
        end: "May-2020",
        city: "Alicante",
        description: "Lorem, ipsum dolor sit amet consectetur adipisicing elit. Repellat, dolor alias. Officia architecto facere voluptates ullam dolore magnam inventore obcaecati earum nostrum, odit hic dolores distinctio sunt corrupti delectus modi.",
    },
    {
        title: "Yoga Instructor",
        employer: "Gavin Belson",
        start: "Jan-2019",
        end: "Current",
        city: "Alicante",
        description: "Lorem, ipsum dolor sit amet consectetur adipisicing elit. Repellat, dolor alias. Officia architecto facere voluptates ullam dolore magnam inventore obcaecati earum nostrum, odit hic dolores distinctio sunt corrupti delectus modi.",
    },
]


const education = [
    {
        degree: "Marketing",
        school: "King Juan Carlos University",
        start: "2014",
        end: "2018",
        city: "Madrid",
        description: "Just a description",
    },
    {
        degree: "Webdev",
        school: "IronHack",
        start: "2020",
        end: "2020",
        city: "Madrid",
        description: "Just a description 2",
    },
    {
        degree: "Mindfulness",
        school: "Life",
        start: "2014",
        end: "2018",
        city: "Madrid",
        description: "Just a description 3",
    },
]


const links = [
    {label: "Prject 1",link: "https://theuselessweb.com/"},
    {label: "Project 2",link: "https://heeeeeeeey.com/"}
]


const templates = [
    {name: "Apollo"},
    {name: "Hermes"},
    {name: "Poseidon"},
    {name: "Zeus"},
    {ame: "Aphodite"},


]

const skills = [
    {skill: "Node.js",level: 2},
    {skill: "JS",level: 3},
    {skill: "React",level: 3},
]

User.create(users)
    .then(allUsers => allUsers.forEach(user => createCVs(user)))
    .then(() => CV.create(cvs))
    .then(() => Template.create(templates))
    .then(() => Description.create({ description: exampleDescription }))
    .then(() => mongoose.connection.close()})
    .catch(error => console.log(error))

As you can see, user.profileDescription property is the exact same Schema as description Model (I made this on purpose: I don't intend to use the description model).

When I run the seed, the description model works perfectly: it creates a single object with all the information stored in it but, regarding the CV Model, I get the following cast Error:

Error [ValidationError]: User validation failed: profileDescription: Cast to string failed for value "[
  {
    type: 'paragraph',
    children: [ [Object], [Object], [Object], [Object], [Object] ]
  },
  {
    type: 'paragraph',
    children: [ [Object], [Object], [Object], [Object], [Object] ]
  },
  { type: 'paragraph', children: [ [Object] ] },
  { type: 'paragraph', children: [ [Object] ] },
  {
    type: 'bulleted-list',
    children: [
      [Object], [Object],
      [Object], [Object],
      [Object], [Object],
      [Object], [Object],
      [Object]
    ]
  },
  { type: 'paragraph', children: [ [Object] ] },
  { type: 'paragraph', children: [ [Object] ] },
  { type: 'paragraph', children: [ [Object] ] }
]" at path "profileDescription"
    at ValidationError.inspect {
  errors: {
    profileDescription: MongooseError [CastError]: Cast to string failed for value "[
      {
        type: 'paragraph',
        children: [ [Object], [Object], [Object], [Object], [Object] ]
      },
      {
        type: 'paragraph',
        children: [ [Object], [Object], [Object], [Object], [Object] ]
      },
      { type: 'paragraph', children: [ [Object] ] },
      { type: 'paragraph', children: [ [Object] ] },
      {
        type: 'bulleted-list',
        children: [
          [Object], [Object],
          [Object], [Object],
          [Object], [Object],
          [Object], [Object],
          [Object]
        ]
      },
      { type: 'paragraph', children: [ [Object] ] },
      { type: 'paragraph', children: [ [Object] ] },
      { type: 'paragraph', children: [ [Object] ] }
    ]" at path "profileDescription"
        at new CastError {
      stringValue: '"[\n' +
        '  {\n' +
        "    type: 'paragraph',\n" +
        '    children: [ [Object], [Object], [Object], [Object], [Object] ]\n' +
        '  },\n' +
        '  {\n' +
        "    type: 'paragraph',\n" +
        '    children: [ [Object], [Object], [Object], [Object], [Object] ]\n' +
        '  },\n' +
        "  { type: 'paragraph', children: [ [Object] ] },\n" +
        "  { type: 'paragraph', children: [ [Object] ] },\n" +
        '  {\n' +
        "    type: 'bulleted-list',\n" +
        '    children: [\n' +
        '      [Object], [Object],\n' +
        '      [Object], [Object],\n' +
        '      [Object], [Object],\n' +
        '      [Object], [Object],\n' +
        '      [Object]\n' +
        '    ]\n' +
        '  },\n' +
        "  { type: 'paragraph', children: [ [Object] ] },\n" +
        "  { type: 'paragraph', children: [ [Object] ] },\n" +
        "  { type: 'paragraph', children: [ [Object] ] }\n" +
        ']"',
      kind: 'string',
      value: [Array],
      path: 'profileDescription',
      reason: null,
      message: 'Cast to string failed for value "[\n' +
        '  {\n' +
        "    type: 'paragraph',\n" +
        '    children: [ [Object], [Object], [Object], [Object], [Object] ]\n' +
        '  },\n' +
        '  {\n' +
        "    type: 'paragraph',\n" +
        '    children: [ [Object], [Object], [Object], [Object], [Object] ]\n' +
        '  },\n' +
        "  { type: 'paragraph', children: [ [Object] ] },\n" +
        "  { type: 'paragraph', children: [ [Object] ] },\n" +
        '  {\n' +
        "    type: 'bulleted-list',\n" +
        '    children: [\n' +
        '      [Object], [Object],\n' +
        '      [Object], [Object],\n' +
        '      [Object], [Object],\n' +
        '      [Object], [Object],\n' +
        '      [Object]\n' +
        '    ]\n' +
        '  },\n' +
        "  { type: 'paragraph', children: [ [Object] ] },\n" +
        "  { type: 'paragraph', children: [ [Object] ] },\n" +
        "  { type: 'paragraph', children: [ [Object] ] }\n" +
        ']" at path "profileDescription"',
      name: 'CastError'
    }
  },
  _message: 'User validation failed',
  name: 'ValidationError'
}

I don't get why is it pointing out a String Cast Error, as I'm using an object for user.profileDescription

Seriously, any help will be really appreciated.

Thank you very much in advance.

Edit:

Thanks to @Thee Sritabtim I spotted the error: The User Model was accepting a String instead of an Array of Objects [{}].

Marked this question as solved.

Thank you everyone.

Solution:

User Model

const mongoose = require("mongoose")
const Schema = mongoose.Schema

const userSchema = new Schema({
    firstName: String,
    lastName: String,
    title: String,
    email: String,
    password: String,
    phone: String,
    profilePicture: String,
    profileDescription: [{}]
}, {
    timestamps: true
})

const User = mongoose.model("User", userSchema)

module.exports = User
6
  • If the user schema is the issue, please include the schema of user as well Commented May 17, 2020 at 12:21
  • @TheeSritabtim the user Schema has been included as the 1st code, labeled as "User Model". Commented May 17, 2020 at 12:29
  • 1
    Your User Model has a statement with mongoose.model("CV", cvSchema), so it's actually CV model Commented May 17, 2020 at 12:32
  • 1
    The error says User validation failed, so I guess we should look there. Commented May 17, 2020 at 12:37
  • 1
    Absolutely: that was the error from the beggining. It seems trivial now, but I had a really bad time spotting it. Thank you very much for your help @TheeSritabtim Commented May 17, 2020 at 12:41

2 Answers 2

1

in the cv schema, you have profileDescription: [{}],

so profileDescription should be an array of objects, but you passed an object { description: exampleDescription }

and I see you passed a string before, but commented

so you need to pass the array exampleDescription directly

const users = [
    {
        firstName: "Example 1",
        lastName: "Last Name 1",
        title: "Student",
        email: "[email protected]",
        password: bcrypt.hashSync('pass1', salt),
        phone: "123456789",
        profilePicture: "https://qph.fs.quoracdn.net/main-qimg-134e3bf89fff27bf56bdbd04e7dbaedf.webp",
        //profileDescription: "Experienced and dedicated Federal Government HR Manager with over ten years of experience, ensure HR systems support agencies in recruiting, hiring and retaining an excellent and diverse workforce. Adept at providing optimal support to executives and officials in need. Committed to integrity and constantly securing the privacy of identities and documents. Bringing forth a proven track record of facilitating excellent workflow in HR departments.",
        profileDescription: exampleDescription, pass the array directly
    },
    {
        firstName: "Demo 1",
        lastName: "Demo 2",
        title: "Yoga Instructor",
        email: "[email protected]",
        password: bcrypt.hashSync('pass2', salt),
        phone: "987654321",
        profilePicture: "https://www.google.com/url?sa=i&url=http%3A%2F%2Fwww.nelsonirrigation.com%2Fmedia%2Fpeople%2F%3FC%3DD%3BO%3DD&psig=AOvVaw2UHc769pta1clyVHKolHF6&ust=1589280988466000&source=images&cd=vfe&ved=0CAIQjRxqFwoTCIj2zZvTq-kCFQAAAAAdAAAAABAi",
        //profileDescription: "Experienced and passionate Yoga Instructor with over five years of teaching experience and advanced training in Ashtanga and Vinyasa approaches. Committed to providing extensive instruction and counseling to my clients, while motivating them to find true inner peace and their healthiest self. Adept in creating powerful teaching plans that aim to support and benefit each and every student. Bringing forth a love and respect for the art of yoga, and all that it encompasses. "
        profileDescription: exampleDescription, // pass the array directly

    },
]

hope it helps

Sign up to request clarification or add additional context in comments.

3 Comments

Hi Mohammed, First of all, thank you for your answer. Unfortunately, I have just tried this as well, and I keep getting the same error. thank you for pointing it out: I passed the old code into the question, but the last test I did was indeed passing the array directly, still doesn't work.
@Togeri if the question has incorrect code, can you correct it? not sure which type do you want exactly, array of objects or object
@TheeSritabtim I already corrected it, sorry for the confusion, apologies. Still, the code gets the same error.
0

Thanks to @Thee Sritabtim I spotted the error: The User Model was accepting a String instead of an Array of Objects [{}].

Marked this question as solved.

Thank you.

Solution:

User Model

const mongoose = require("mongoose")
const Schema = mongoose.Schema

const userSchema = new Schema({
    firstName: String,
    lastName: String,
    title: String,
    email: String,
    password: String,
    phone: String,
    profilePicture: String,
    profileDescription: [{}]
}, {
    timestamps: true
})

const User = mongoose.model("User", userSchema)

module.exports = User

The key was the terminal error, as pointed out by @Thee Sritabtim: User validation failed , which lead to the User Model revision and the following error spotting.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.