Mongoose/Node: push element into document field of type array?

Viewed 53

I have a Mongoose schema with a field of type array, intended for containing several strings:

const exampleSchema = new.mongooseSchema({
      field1: String,
      field2: String,
      field3: [String]
})

I am setting up the backend to concatenate/push new strings into the field3 array, hoping to get something like this:

{
   field1: 'some string',
   field2: 'some other string',
   field3: [
              'string inside array1',
              'string inside array2',
              'string inside array3',
           ]
}

I am trying to do this with findByIdAndUpdate() an was trying things like spread operators to concatenate new strings into field 3, but I am not fully sure of how to use the syntax.

Is there any clean way of doing this without having to create an new updated object to replace the entire document?

2 Answers

You only need $push.

Check this example to know the syntaxis.

Using mongo is like this

db.collection.update({
  /* Your find object*/
},
{
  "$push": {
    "field3": "another string"
  }
})

Using $push you can add a value into an array. Easy.

And using moongoose is exactly the same, you have to pass the push object into parameters.

model.findByIdAndUpdate(your_id, {
  "$push": {
    "field3": "another string"
  }
})

How I have learned to update a small part of an item in mongoose is the following:

const example = await exampleSchema.findById(id)

// Return if non existing
if (!example )
  return res
    .status(404)
    .send(`Example with id:${id} was not found.`)

// Sets the new field3
example.field3 = [...example.field3, req.body.addedField3]

try {
  const result = await example.save()
  res.send(result)
} catch (exeption) {
  res.status(400).send(exeption.message)
}

This is wrapped in a router.put from express.Router

Related