Change a single value of a subdocument in mongodb - node.js

I have a Model called Notes. It has a subdocument requests which holds various documents with values userId, reqType, accepted value( false by default) and noteId of the sender, request and note respectively. When the user hits a certain route I want to keep all the data to be as their previous values, just updating the accepted field to true.
The below code leads to no change in the data or a different iteration leads to erasing all the data other than accepted field and modifying it to true.
How should I do this?
const noteSchema = new mongoose.Schema(
requests: [
{
userId: mongoose.Schema.ObjectId,
noteId: mongoose.Schema.ObjectId,
reqType: String,
accepted: {
type: Boolean,
default: false,
},
},
],
}
)
const Note = mongoose.model('Note', noteSchema)
const note = await Note.findById(req.body.noteId)
await note.updateOne({
requests: {
$elemMatch: {
userId: req.body.userId,
reqType: req.body.reqType,
noteId: req.body.noteId,
},
$set: { "requests.$.accepted": true },
},
})

You do not need to retrieve the document and then update it. Just update it. Use this one:
await Note.updateOne(
{
"requests.userId": req.body.userId,
"requests.reqType": req.body.reqType,
"requests.noteId": req.body.noteId
},
{
$set:
{
"requests.$.accepted":true
}
}
);
I checked, it worked.
With first part mongoose will find the document, with $set it will be updated.

Related

Concurrency problems updating another's collection stats

I'm trying to make a notation system for movies
A user can note a Movie in their List.
Whenever the user clicks on the frontend, the listId, movieId, note are sent to the server to update the note. The note can be set to null, but it does not remove the entry from the list.
But if the user clicks too much times, the movie's totalNote and nbNotes are completely broken. Feels like there is some sort of concurrency problems ?
Is this the correct approach to this problem or am I updating in a wrong way ?
The mongoose schemas related :
// Movie Schema
const movieSchema = new Schema({
// ...
note: { type: Number, default: 0 },
totalNotes: { type: Number, default: 0 },
nbNotes: { type: Number, default: 0 },
})
movieSchema.statics.updateTotalNote = function (movieId, oldNote, newNote) {
if (!oldNote && !newNote) return
const nbNotes = !newNote ? -1 : (!oldNote ? 1 : 0) // If oldNote is null we +1, if newNote is null we -1
return Movie.findOneAndUpdate({ _id: movieId }, { $inc: { nbNotes: nbNotes, totalNotes: (newNote - oldNote) } }, { new: true }).catch(err => console.error("Couldn't update note from movie", err))
}
// List Schema
const movieEntry = new Schema({
_id: false, // movie makes an already unique attribute, which is populated on GET
movie: { type: Schema.Types.ObjectId, ref: 'Movies', required: true },
note: { type: Number, default: null, max: 21 },
})
const listSchema = new Schema({
user: { type: Schema.Types.ObjectId, ref: 'Users', required: true },
movies: [movieEntry]
})
The server update API (add / Remove movieEntry are similar with $push and $pull instead of $set)
exports.updateEntry = (req, res) => {
const { listId, movieId } = req.params
const movieEntry = { movieId: movieId, note: req.body.note }
List.findOneAndUpdate({ _id: listId, 'movies.movie': movieId }, { $set: { 'movies.$[elem]': movieEntry } }, { arrayFilters: [{ 'elem.movie': movieId }] })
.exec()
.then(list => {
if (!list) return res.sendStatus(404)
const oldNote = list.getMovieEntryById(movieId).note // getMovieEntryById(movieId) = return this.movies.find(movieEntry => movieEntry.movie == movieId)
Movie.updateTotalNote(movieId, oldNote, movieEntry.note)
let newList = list.movies.find(movieEntry => movieEntry.movie == movieId) // Because I needed the oldNote and findOneAndUpdate returns the list prior to modification, I change it to return it
newList.note = movieEntry.note
newList.status = movieEntry.status
newList.completedDate = movieEntry.completedDate
return res.status(200).json(list)
})
.catch(err => {
console.error(err)
return res.sendStatus(400)
})
}
The entries I needed to update were arrays that could grow indefinitely so I had to first change my models and use virtuals and another model for the the list entries.
Doing so made the work easier and I was able to create, update and delete the entries more easily and without any concurrency problems.
This might also not have been a concurrency problem in the first place, but a transaction problem.

Update Mongoose Array

so basically I have this and I am trying to update the STATUS part of an array.
However, everything I try does nothing. I have tried findOneAndUpdate also. I am trying to identify the specific item in the array by the number then update the status part of that specific array
(Sorry for formatting, I have no idea how to do that on the site yet ...) (Full code can be found here: https://sourceb.in/0811b5f805)
Code
const ticketObj = {
number: placeholderNumber,
userID: message.author.id,
message: m.content,
status: 'unresolved'
}
let tnumber = parseInt(args[1])
let statuss = "In Progress"
await Mail.updateOne({
"number": tnumber
}, { $set: { "status": statuss } })
Schema
const mongoose = require('mongoose')
const mailSchema = new mongoose.Schema({
guildID: { type: String, required: true },
ticketCount: { type: Number, required: true },
tickets: { type: Array, default: [] }
}, { timestamps: true });
module.exports = mongoose.model('Mail', mailSchema)
You need to use something like Mail.updateOne({"guildID": message.guild.id}, {$set: {`tickets.${tnumber}.status`: statuss}})
or for all objects in array:
Mail.updateOne({"guildID": message.guild.id}, {$set: {'tickets.$[].status': statuss}})
Also, you need to create a schema for the tickets, as it is described in docs:
one important reason to use subdocuments is to create a path where there would otherwise not be one to allow for validation over a group of fields

MongoDB - update data in array of objects within object

I have a document in mongoDB structured like that
_id: ObjectId("generatedByMongo"),
name: {
required: true,
type: String,
trim: true
},
last: {
required: true,
type: String,
trim: true
},
grades: [{
grade: {
_id: ObjectId(""),
grade: Number,
date: date
}
}]
And to server I send array of objects containing 3 fields
[
{studentId}, {gradeId}, {newGrade}
]
What I'm trying to accomplish is I want to find in within that user collection grade with given gradeId and update it's value to newGrade. As far as I tried to do that I have done this
router.patch('/students/updateGrade',async(req,res) => {
const studentId = req.body.updateGradeArray[0].studentId;
const gradeId = req.body.updateGradeArray[0].gradeId;
const newGrade = req.body.updateGradeArray[0].newGrade;
try {
const student = await Student.find({_id: studentId})
.select({'grades': {$elemMatch: {_id: gradeId}}});
} catch(e) {
console.log(e);
}
}
);
If you intend to update just grade.grade(the number value), try this:
Student.updateOne(
// Find a document with _id matching the studentId
{ "_id": studentId },
// Update the student grade
{ $set: { "grades.$[selectedGrade].grade": newGrade } },
{ arrayFilters: [{ "selectedGrade._id": gradeId }] },
)
Why this should work:
Since you are trying to update a student document, you should be using one of MongoDB update methods not find. In the query above, I'm using the updateOne method. Inside the updateOne, I am using a combination of $set and $[identifier] update operators to update the student grade.
I hope this helps✌🏾

Mongoose — findOneAndUpdate() causing document duplication

I'm using findOneAndUpdate() with upsert: true in order for a document to be updated if it exists and to be created otherwise. The tracks variable contains an array of Track instances. tracks does contain a few duplicates and that's where the problem begins. It causes the piece of code on line 7 (Observation.findOneAndUpdate(...)) to create a (low) number of duplicates, i.e. multiple documents that have the same (user, track) pair. Note that those duplicates are inserted randomly: running twice this piece of code brings different duplicated documents. My guess is that it has something to do with how the locking of data is done in MongoDB and that I'm doing too many operations at the same time. Any idea on how I could overcome this problem?
const promises = [];
​
tracks.forEach((track) => {
const query = { user, track };
const options = { new: true, upsert: true };
const newOb = { user, track, type: 'recent' };
promises.push(Observation.findOneAndUpdate(query, newOb, options));
});
​
return Promise.all(promises);
I'm using mongoose 5.5.8 and node 11.10.0.
Here's the Observation model:
const { Schema } = mongoose;
const ObservationSchema = new Schema({
track: { type: Schema.Types.ObjectId, ref: 'Track' },
user: { type: Schema.Types.ObjectId, ref: 'User' },
type: String
});
ObservationSchema.index({ track: 1, user: 1 }, { unique: true });
const Observation = mongoose.model('Observation', ObservationSchema);
And this is a sample of what the tracks array contains:
[
{ artists: [ 5da304b140185c5cb82d7eee ],
_id: 5da304b240185c5cb82d7f48,
spotifyId: '4QrEErhD78BjNFXpXDaTjH',
__v: 0,
isrc: 'DEF058230916',
name: 'Hungarian Dance No.17 In F Sharp Minor',
popularity: 25 },
{ artists: [ 5da304b140185c5cb82d7eee ],
_id: 5da304b240185c5cb82d7f5d,
spotifyId: '06dn1SnXsax9kJwMEpgBhD',
__v: 0,
isrc: 'DEF058230912',
name: 'Hungarian Dance No.13 In D',
popularity: 25 }
]
Thanks :)
I think this is due to your Promise.all method.
You should await every single query in the loop instead of awaiting everything at the same time at the end. Here an example with find:
async function retrieveApples() {
const apples = [];
arr.forEach(apple => {
const foundApple = await AppleModel.findOne({ apple });
apples.push(foundApple);
});
return apples
}

Delete an array element from a document with Mongoose

I am having a schema called ReferralHistory.
It contains set of users and array of referred users.
ReferralHistory
var mongoose = require('mongoose');
var refferalHistorySchema = new mongoose.Schema({
user: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User',
unique: true
},
referrals: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
}],
});
var ReferralHistoryModel = mongoose.model('ReferralHistory', refferalHistorySchema);
module.exports = {
referralHistory: ReferralHistoryModel
}
I need to delete a particular user from referrals array in the collection ReferralHistory[Here i only know id of referred user].How can i achieve this?
Edit
Collection
I tried
db.referralhistories.update({ "u_referrals": "593281ef966d7f0eeb94db3d" }, { "$pull": { "u_referrals": "593281ef966d7f0eeb94db3d" } });
O/P
But document is not updating.
You use the $pull operator with .update(). So assuming referredId as the value you know
ReferralHistoryModel.update(
{ "referrals": referredId },
{ "$pull": { "referrals": referredId } },
{ "multi": true },
function(err,status) {
}
)
Noting the { "multi": true } means the update can be applied to more than one matched document in the collection. If you really only intend to match and update one document then you don't include that option since updating only the first match is the default.
If you want to be more specific and also have the "user" to match, then you can do:
ReferralHistoryModel.update(
{ "user": userId, "referrals": referredId },
{ "$pull": { "referrals": referredId } },
{ "multi": true },
function(err,status) {
}
)
And then the match needs both values to be present as opposed to any ReferralhistoryModel documents which matched the referredId you supplied.

Resources