findOneAndUpdate на мангусте, чтобы обновить массив внутри документа или создать новый документ
У меня есть эта схема
import mongoose from 'mongoose'
const logSchema = mongoose.Schema({
fair: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Fair',
required: true
},
email: {
type: String,
unique: true,
required: true,
},
user: {
name: {
type: String,
required: true,
},
others: {
type: String,
}
},
action: [{
type: {
type: String,
required: true,
},
title: {
type: String,
required: true,
},
actionDate: {
type: Date,
default: Date.now(),
},
others: {
type: String,
}
}],
createdAt: {
type: Date,
default: Date.now(),
}
})
logSchema.index({ email: 1 })
export default mongoose.model('Log', logSchema)
Теперь я хочу обновить массив действий. Что-то вроде этого
Log.findOne({
email: req.body.email
})
.then( log => {
const newAction = {
type: req.body.action.type,
title: req.body.action.title,
others: req.body.action.others
}
// Add to action array
log.action.unshift(newAction);
log.save()
.then( log => {
res.status(200).json(log);
});
})
.catch( err => console.log(err));
});
И когда документ не существует, я хочу создать новый, похожий на этот
const log = {
fair: req.headers['fair-api-key'],
email: req.body.email,
user: {
name: req.body.user.name,
others: JSON.stringify(req.body.user.others)
},
action: {
type: req.body.action.type,
title: req.body.action.title,
others: JSON.stringify(req.body.action.others)
}
}
const newLog = new Log(log)
try {
await newLog.save()
res.status(201).json(newLog)
} catch (error) {
res.status(409).json({ message: error.message })
}
Я исследовал и нашел метод мангуста findOneAndUpdate, но не могу заставить его работать. И я хочу сделать что-то подобное, потому что, когда документ уже существует, я не хочу иметь возможность изменить user.name или user.others. После создания единственное, что должно иметь возможность обновляться, — это массив действий.