I am trying to create a heatmap using react-d3-heatmap and it needs data as [{date: Date, count: Number}].
This is my model.
const HeatMapSchema = new mongoose.Schema({
user: {type: mongoose.Schema.ObjectId, ref: 'User'},
data: [{
date: {
type: Date,
default: Date.now
},
count: {
type: Number,
default: 0
},
}]
})
I have tried a bunch of different ways to query the document that pertains to the correct user and then go into the data to query the date and increment the count. I installed moment.js to help query the date. Can you help me find the model matching the user and update the count for that day within the data object? Thanks
import HeatMap from '../models/heatmap.model'
import errorHandler from './../helpers/dbErrorHandler'
import moment from 'moment'
const addDate = async (req, res) => {
const id = '60e88ceaa331a63d2c9523fc'
const today = moment().startOf('day')
try {
let data = await HeatMap
.find({user: id})
.updateOne({data: {date: {$gte: today.toDate(), $lte: moment(today).endOf('day').toDate()}}}, {count: 1})
res.json(data)
} catch (err) {
return res.status(400).json({
error: errorHandler.getErrorMessage(err)
})
}
}
export default {
create,
getHeatMapData,
addDate
}
found a way.
const addDate = async (req, res) => {
const id = '60e88ceaa331a63d2c9523fc'
const today = moment().startOf('day')
try {
const query = { user: id, "data.date": {
$gte: today.toDate(),
$lte: moment(today).endOf('day').toDate()}
}
const updateDocument = {
$inc: { "data.$.count": 1 }
};
let data = await HeatMap.find({$and: [
{user: id}, {"data": {$gte: today.toDate()}}
]})
if (data.length === 0) {
await HeatMap.updateOne({user: id}, {"$push": {"data": {'count': 0}}})
} else {
data = await HeatMap.updateOne(query, updateDocument)
}
res.json(data)
} catch (err) {
return res.status(400).json({
error: errorHandler.getErrorMessage(err)
})
}
}
in updateOne use this :
updateOne({$set:{"data.$[elem].count": 1}},
{$arrayFilters:[{"elem.date": {$gte: today.toDate(), $lte: moment(today).endOf('day').toDate()}}]})