I am trying to represent a grid structure within a MongoDB. I am having trouble updating a nested object. More specifically, the columns array located within the layouts rows row array element. I have created the following models:
layoutModel.js
const LayoutSchema = new mongoose.Schema({
rows: {
type : Array , "default" : []
},
})
rowModel.js
const RowSchema = new mongoose.Schema({
columns: {
type : Array , "default" : []
},
user_id: {
type: String,
unique: false,
},
layout_id: {
type: String,
unique: false,
}
})
columnModel.js
const ColumnSchema = new mongoose.Schema({
column: {
type : Array , "default" : []
},
user_id: {
type: String,
unique: false,
},
layout_id: {
type: String,
unique: false,
}
})
I am able to find the layout associated with the current user, and then add a new row to the layout database object.
server.js
// database models
const Layout = require("./database/models/layout.js")
const User = require("./database/models/userModel.js")
const Row = require("./database/models/rowModel.js")
const Column = require("./database/models/columnModel.js")
app.post('/add-row', jsonParser, (req, res) => {
User.findOne({ _id: req.body.profile_id })
.then((user) => {
const new_row = new Row({columns: [],}) //create new row database object
new_row.save() //save object
//find user's layout database object
Layout.findOne({_id:user.layout_id}).then((layout) => {
//found user's layout
layout.rows = [new_row, ...layout.rows] //add new row to array of all the old rows
layout.save() //save object
})
})
res.send('Add row')
})
However, when I try to add a new column to the row within the layouts rows array it does not update in the database. I am not sure why.
app.post('/add-column', jsonParser, (req, res) => {
User.findOne({ _id: req.body.profile_id })
.then((user) => {
//user is logged in so get the users layout
Layout.findOne({_id:user.layout_id})
.then((layout) => {
//found layout
for(let row in layout.rows){
let row_id = layout.rows[row]._id.toString() //current row's id
if(row_id === req.body.var_row_id){ //found row to add column to
const new_column = new Column({column: [],}) //create new column database object
new_column.save()
layout.rows[row].columns = [...layout.rows[row].columns, new_column] //add new column to array of all the old columns
layout.save()
}
}
})
})
})
Any advice is greatly appreciated.