findOneAndUpdate иногда обновляет, а иногда нет
Хорошо, у меня есть следующая схема
const newUserSchema = new mongoose.Schema({
name: {
type: String,
required: [true, "Check Data Entry, no name specified"]
},
email: {
type: String,
required: [true, "Check Data Entry, no email specified"]
},
password: {
type: String,
// required: [true, "Check Data Entry, no password specified"]
},
kids: []
});
затем я создал новую детскую схему
const newKidSchema = new mongoose.Schema({
name: {
type: String,
required: [true, "Check Data Entry, no name specified"]
},
age: {
type: Number,
required: [true, "Check Data Entry, no age specified"]
},
gender: {
type: String,
required: [true, "Check Data Entry, no level specified"]
},
experiencePoints: {
type: Number
},
gameScores: [],
learningResources: [],
progress: [],
engPlanner: [],
urduPlanner: [],
mathPlanner: [],
dates: [],
dayTaskLength:[]
});
const learningResources = new mongoose.Schema({
name: {
type: String,
required: [true, "Check Data Entry, no name specified"]
},
subject: {
type: String,
required: [true, "Check Data Entry, no subject specified"]
},
status: {
type: Boolean,
required: [true, "Check Data Entry, no status specified"]
},
learningTime: {
type: String,
required: [true, "Check Data Entry, no time specified"]
}
});
const gameScoreSchema = new mongoose.Schema({
subject: {
type: String,
required: [true, "Check Data Entry, no subject specified"]
},
gameTitle: {
type: String,
required: [true, "Check Data Entry, no Game Title specified"]
},
gameScore: {
type: Number,
required: [true, "Check Data Entry, no Game Score specified"]
},
gameTime: {
type: String,
required: [true, "Check Data Entry, no Game Time specified"]
},
experiencePoints: {
type: Number,
required: [true, "Check Data Entry, no Experience Points specified"]
},
gameStatus: {
type: Boolean,
required: [true, "Check Data Entry, no Game Status specified"]
}
});
const progressSchema = new mongoose.Schema({
engGamesProgress:{
type: Number,
required: [true]
},
mathGamesProgress:{
type: Number,
required: [true]
},
urduGamesProgress:{
type: Number,
required: [true]
},
engLrProgress:{
type: Number,
required: [true]
},
mathLrProgress:{
type: Number,
required: [true]
},
urduLrProgress:{
type: Number,
required: [true]
}
});
И это код, в котором я получаю данные gameScore,
app.post("/add-game-score", (req, res) => {
// New game
const newSubject = req.body.subject;
const newTitle = req.body.gameTitle;
const newGameScore = req.body.gameScore;
const newGameTime = req.body.gameTime;
const newExperiencePoints = req.body.experiencePoints;
const newgameStatus = req.body.gameStatus;
User.findOne({
email: signedInUser
}, function(err, foundList){
if(!err){
if(foundList){
kids = foundList.kids;
const newgame = new GameScore({
subject: newSubject,
gameTitle: newTitle,
gameScore: newGameScore,
gameTime: newGameTime,
experiencePoints: newExperiencePoints,
gameStatus: newgameStatus
});
// var new_kids = [];
kids.forEach(kid => {
if(kid._id == kidProfileCurrentlyIn.kidID){
kid.gameScores.push(newgame)
console.log("Bellow are all game scores");
console.log(kid.gameScores);
}
// new_kids.push(kid);
});
gameKidsArray = kids;
User.findOneAndUpdate({
email: signedInUser
}, {
kids:gameKidsArray
}, (err, foundList) => {
if(foundList){
console.log(gameKidsArray);
console.log("Added Game Successfully");
console.log(foundList);
}
});
}
}
});
});
Теперь проблема в том, что когда я использую массив console.log kid.gameScores, я нахожу в нем свой недавно добавленный счет, но когда я использую console.log (kids), он не обновляется. В mongodb Atlas я не могу найти новые игровые результаты. Но проблема в том, что время от времени они попадают в базу данных. Я так сбит с толку, почему возникает эта проблема. Я знаю, что отправляю правильные данные, и они обновляются в массиве kid.gameScores, но "Kid" не обновляется с новым массивом gamescore.
User.findOneAndUpdate({
email: signedInUser
}, {
kids:gameKidsArray
}
здесь я обновляю свои массивы. Любая помощь.
1 ответ
Если вы хотите убедиться, что
findOneAndUpdate
успешно обновил вашу запись, вам нужно добавить
{ new: true }
в последнем параметре. Смотрите здесь.
Поэтому вам следует обновить свои коды, чтобы они были
User.findOneAndUpdate({
email: signedInUser
}, {
kids:gameKidsArray
}, {
new: true
}