使用节点保存数据时,Req.body 未从模式中获取数组值

分享于2022年07月17日 angular express mongoose node.js 问答
【问题标题】:使用节点保存数据时,Req.body 未从模式中获取数组值(Req.body not fetching array value from schema when save data using node)
【发布时间】:2022-01-24 22:58:10
【问题描述】:

当我使用 MongoDB 模式数组中的节点保存数据时,我的代码和输出将是空的,请您解释为什么会发生此错误

controller.js

  const {name,age,social,songs}=new musicModel(req.body)
  
  const addMusic =await musicModel.create({
   name,age,songs,social
  })

  if (addMusic) {
    res.send(addMusic)
  } else {
    res.status(500).send("unsuccessfull.")
  }
}

这是我的架构,但是当我使用邮递员发送响应时它会完美工作,但是当我保存它时,波纹管数组未定义或为空

model.js

const mongoose = require("mongoose")
const songSchema= mongoose.Schema({
  title:{
    type:String
  },
  sales:{
    type:String
  }
})
const musicSchema = mongoose.Schema({
  name: {
    type: String
  },
  age: {
    type: String
  },
  social: {
    show: {
      type: Number
    }, tours: {
      type: Number
    },
  },songs:[songSchema]
})
const musicModel =mongoose.model("Music",musicSchema)
module.exports= musicModel

app.js

const express = require('express')
const logger = require('morgan')
const bodyParser = require('body-parser')
const mongoose = require('mongoose')
require("dotenv/config")

const cors = require('./middleware/cors')

const productsRouter = require('./routes/products')
const customerRouter= require('./routes/customers')
const quotRouter=require('./routes/quots')
const usersRouter = require('./routes/users')

mongoose.connect(
  process.env.CONNECTION_URL,
  { useNewUrlParser: true },
  (err) => {
    if (!err) {
      console.log('DB Connected')
    }
  }
);

const app = express()
app.use(express.static('public'))

app.use(logger('dev'))


app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended:true}))
app.use(cors)

app.use('/products', productsRouter)
app.use('/customer',customerRouter)
app.use('/', usersRouter)
app.use('/quotation',quotRouter)

module.exports =app;

输出

{
    "name": "ashit",
    "age": "67",
    "social": {
        "show": 566,
        "tours": 47
    },
    "songs": [],
    "_id": "61c57a22a6903d467834d19f",
    "__v": 0
}


【解决方案1】:

您可以在这两种类型的代码之间进行选择:

第一个解决方案:

  const {name,age,social,songs}=req.body
  
  const addMusic =await musicModel.create({
   name,age,songs,social
  })

  if (addMusic) {
    res.send(addMusic)
  } else {
    res.status(500).send("unsuccessfull.")
  }
}

第二种解决方案:

 const {name,age,social,songs}=new musicModel(req.body)
  
  const addMusic =await musicModel.save()

  if (addMusic) {
    res.send(addMusic)
  } else {
    res.status(500).send("unsuccessfull.")
  }
}