I want to insert data in mongodb where one field is of array of an objects type.I am unable to get how I can add data into array field along with other fields defined in mongoose schema. When I am trying to post data using POSTMAN with below configurations as shown in screenshot:
Its showing games array is empty and showing below error
games: CastError: Cast to embedded failed for value "'San and'" (type string) at path "games"
Below is my code:
db.js
const mongoose = require('mongoose');
const dotEnv = require('dotenv').config();
const uri = process.env.URI;
const connect = mongoose.connect(uri,{useNewUrlParser:true,useUnifiedTopology:true})
.then(() => console.log("Database connected"))
.catch((err) => {
console.log("Something went wrong",err);
process.exit(1);
});
module.exports = connect;
publisher.js
const mongoose = require('mongoose');
const publisherSchema = new mongoose.Schema({
company_name:{
type: String
},
website:{
type: String
}
games: [{
date: Date,
name: String
}]
});
const publisher = mongoose.model('Publisher',publisherSchema);
module.exports = publisher;
Two fields can be inserted as given in below code but How Can I add array field along with these two fields.
server.js
const express = require('express');
const connect = require('./db.js');
const publisher = require('./models/publisher.js');
const gaming = require('./models/game.js');
const app = express();
const port = process.env.PORT || 3000;
app.use(express.json());
app.use(express.urlencoded({ extended: true }))
app.post('/publish',async (req,res) => {
const { company_name,website,games } = req.body;
const insert = new publisher({company_name,website,games});
try{
const data = await insert.save();
res.send(data);
}
catch(err){
console.log(err);
}
});
app.listen(port, () => console.log(`App is up and runnning at ${port}`));
Someone let me know how can I perform this task.