Mongoose - Automatically add object to array

Hi there folks,
I have this code:

            .findOneAndUpdate({ projectname: item }, {responsetime: [{timestamp: secondsSinceEpoch, pingtime: res.ping_time}]})
            .then(function() {
              console.log("Should have updated with timestamp and ping time!");

But the problem is that this overwrites responsetime and pingtime in the database. Any way I can make a new object instead of overwriting?
My schema looks like this:

var schema2 = new mongoose.Schema({
  email: "string",
  name: "string",
  projectname: "string",
  dashID: "string",
  pingStatus: "string",
  responsetime: [{timestamp: String, pingtime: String}],
  glitch: "boolean"

But I don’t want to have to add a new object to the schema. I want this to be done automatically. (Should be [{timestamp: String, pingtime: String}, {timestamp: String, pingtime: String}] etc.) Any ideas on how to do this? Can you put me in the right direction (e.g. specific parts of docs about this)

Was sent this on Reddit:

You’ll want to use the $push operator. Take a look:

Looks like it’s what I need using this method:

1 Like

Next time when you face a problem, think and try to find the answer and ask here only if you’ve tried so much because the last few threads, you’ve solved it yourself. :wink::grin::+1: But good job exploring and finding the answer on your own!


Well, in this case I put the question on Reddit as well as here and someone on Reddit answered. I just thought it might be better to show the answer here in case anyone was wondering :slight_smile: I agree though sometimes I do fix it myself or it’s a simple spelling error - will work on my proof-reading and Googling skills :joy:

1 Like

It’s not just you, until two months ago I used to ask people my code problems but then in the end I’ll solve it on my own. When I started realising it, I stopped asking people and I try my best to solve it on my own. :blush:


Clever thinking :joy:

1 Like