When I'm saving the data using node in my MongoDB schema array would be empty here my code and output could you please explain why this error happening
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.")
}
}
Here's my schema but it will perfectly work when I send response using postmen but when I saved this the bellow array was undefined or null
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;
output
{
"name": "ashit",
"age": "67",
"social": {
"show": 566,
"tours": 47
},
"songs": [],
"_id": "61c57a22a6903d467834d19f",
"__v": 0
}
CodePudding user response:
Try to save the songs
using a push
after the object creation:
const { name, age, social, songs } = new musicModel(req.body);
const addMusic = new musicModel({
name,
age,
social,
});
addMusic.songs.push(songs)
await addMusic.save();
if (addMusic) {
res.send(addMusic);
} else {
res.status(500).send("unsuccessfull.");
}
CodePudding user response:
You have the choice between theses two types of code :
First Solution :
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.")
}
}
Second solution :
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.")
}
}