Answer the question
In order to leave comments, you need to log in
$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');
},
);
});
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 },
}],
}],
});
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});
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question