MongoDB为什么在对象数组上将错误类型转换为String类型?

编程入门 行业动态 更新时间:2024-10-05 21:21:58

MongoDB为什么在对象数组上将错误<a href=https://www.elefans.com/category/jswz/34/1771355.html style=类型转换为String类型?"/>

MongoDB为什么在对象数组上将错误类型转换为String类型?

由于以下错误,我感到非常困惑,因为对我来说这几乎一样。

运行猫鼬种子,我有以下模型:

用户模型

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型号

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

描述模型

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

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

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

module.exports = Description

种子

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: ".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: ";url=http%3A%2F%2Fwww.nelsonirrigation%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: "/"},
    {label: "Project 2",link: "/"}
]


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

您可以看到,user.profileDescription属性与描述模型是完全相同的模式(我是故意这样做的:我不打算使用描述模型)。

[运行种子时,描述模型运行完美:它创建了一个对象,其中存储了所有信息,但是对于CV模型,我得到以下强制转换错误:

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'
}

我不知道为什么它指出了一个字符串转换错误,因为我正在使用user.profileDescription的对象

非常感谢您的帮助。

非常感谢。

回答如下:

在简历模式中,您有profileDescription: [{}]

所以profileDescription应该是对象数组,但是您传递了一个对象{ description: exampleDescription }

并且我看到您之前传递了一个字符串,但已评论

所以您需要直接传递数组exampleDescription

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/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/url?sa=i&url=http%3A%2F%2Fwww.nelsonirrigation%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

    },
]

希望有帮助

更多推荐

MongoDB为什么在对象数组上将错误类型转换为String类型?

本文发布于:2024-05-13 09:03:12,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1759332.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:类型   数组   上将   转换为   对象

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!