M
M
marks262020-04-05 01:04:32
MongoDB
marks26, 2020-04-05 01:04:32

$push is duplicated when querying findOneAndUpdate in mongoose, what's wrong?

When trying to add data to the database, $push for some reason duplicates them in the field, i.e. the field with an array called dates in the database should eventually have 21 array elements after sending the data, but in fact there are 42 of them. The data is duplicated.

Database request code:

router.post('/set-new-activities', async (req, res) => {
  const { id, activities } = req.body;

  console.log(id);
  console.log(activities);

  await UserCalendar.findOneAndUpdate(
    { _id: new ObjectId(req.session.userId), actions: { $elemMatch: { _id: id } } },
    { $push: { 'actions.$.dates': activities } },
    (err) => {
      if (err) throw err;

      console.log('success');

      res.json('success');
    },
  );
});

Scheme:
const { Schema, model } = require('mongoose');

const schema = new Schema({
  name: {
    type: String,
    required: true,
  },
  password: {
    type: String,
    required: true,
  },
  actions: [{
    name: { type: String },
    days: [],
    debt: { type: Boolean, default: false },
    created: { type: Date, default: '2020-03-16' },
    status: { type: Boolean, default: true },
    dates: [{
      year: { type: String },
      month: { type: String },
      day: { type: String },
      status: { type: Boolean, default: false },
    }],
  }],
});

POST request code to the server:
const obj = {
        id: action._id,
        activities: newActivity,
      };

      const response = await fetch('/set-new-activities', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json;charset=utf-8',
        },
        body: JSON.stringify(obj),
      });

      if (response.ok) {
        console.log('Активность обновлена');
      } else {
        throw new Error(Возникла проблема с fetch запросом. ${response.status});
      }


Here's what we end up with in the database:
5e89031c8ca0f430808479.png

And this is what the console.log on the server gave out:
5e8903f51bb57118792911.png

There are no errors, and the object itself with the data was sent once. Perhaps I screwed up somewhere in the query to the database. because I'm just getting used to mongoose.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
marks26, 2020-04-05
@marks26

In short, instead of $push I used $addToSet and duplication stopped

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question