I am attempting to update a value within an array of objects when receiving a specific post from a user. However, it seems to only update when the matching value is the first element in the array. If the matching object is the first element in the array, it updates as expected. If it is not the first element, it is not updated. Replacing this with findOne() returns the object as expected. Am I missing something with how the $ operator works?
const response = await client
.db("auth")
.collection("users")
.findOneAndUpdate(
{
_id: new ObjectID(req.body.userId),
"assignments.type": req.body.type,
"assignments.number": req.body.number
"assignments.complete": false
},
{
$set: {
"assignments.$.complete": true,
"assignments.$.id": result.insertedId, // Previous call, is populated as expected
}
},
{
returnDocument: "after",
}
);
The document returned has the relevant value as false as is response.value.
Related
Hi I tried to update the element at a particular index in an array but I'm not able to update it. It is updating the entire array. Not able to figure out how to update any particular index. Also tried
{$set:{"Data.1:req.body}}
this is updating at 1st index but I don't want to hardcode the index value. It should take from frontend. Let say I have a schema in which I have Data who's type is array and default value is as shown below or anything in the same format.
Data: {
type: Array,
Default: ["0","1","0"]
}
Whenever I'll create a user then Data field will contain these default values, But now I want to update the value at any index (coming from frontend) of Data array of any user created.
I tried findByIdAndUpdate method but I don't know what to pass in set property. If I'm passing this {$set: req.body} and In postman I'm giving any value of Data then obviously it is updating Data array but I want to update value at any index which I'm passing from frontend, let say the index I'm passing is 2 then it should update the value of array at index 2, similarly I can pass any index from frontend how should I do that. What changes I have to make in {$set : } Thanks in advance.
Waiting for any help or suggestions. Thanks
It appears that you can solve this in backend logic if you are passing the index from the frontend.
You can dynamically specify the index, based on the input from the frontend, before you send a query.
const updateUserData = async (req, res) => {
const { index, user_id, new_value } = req.body;
try {
const update = {};
update[`Data.${index}`] = new_value;
const data = await Users.updateOne(
{ _id: user_id },
{ $set: update }
);
return res.status(200).json({ success: true });
} catch (error) {
return res.status(500).json({ success: false });
}
};
Im working on an API for a custom game and i need to update specific fields in an array in my Database Entry. How do i do that without adding a new thing to the array, instead just updating for example the content of entry 5 in the array
Hello I'm not sure the name of your schema so I'm assuming its called Game so here is an example for how to update an index in an array assuming its the board array field you're trying to update. Also reference here for more details on updating an array field by it's index:
var fieldPosition = "board." + req.params.field
await Game.updateOne({
_id: 1
}, [{
$set: {
tempBoard: fieldPosition
}
},
{
$set: {
"$tempBoard": session.turn
}
},
{
$unset: ["tempBoard"]
}
])
I have built an API that updates records in MongoDB using mongoose, but currently what happening is if I am passing only 4 field values in the JSON file of postman and try to update then all the values are updating with value null except that 4 fields which I had passed in JSON so can anyone help me how I can pass dynamic field and value that update only passed values of collection not all the fields of collection.
Passes JSON :
{
"preferance_id" : "60fe9ba1766d10d65c64083c",
"is_active": true,
"price_blur":true,
"affiliate_commission":27,
"language_code": "en"
}
Update call which I have passed in node js
transaction.update(PreferencesMasterName,
{ _id: new mongoose.Types.ObjectId(preferance_id) }, {
subscriptin_vat : subscriptin_vat,
popular_normal : popular_normal,
popular_crawled : popular_crawled,
price_blur : price_blur,
blur_rule : blur_rule,
affiliate_commission : affiliate_commission,
red_lock : red_lock,
automatic_dummy_price : automatic_dummy_price,
...
is_active: is_active
})
I want to pass dynamic field and values here instead of this because due to this other values are set will null value. So, can anyone have an idea how to do this?
You can do something like this:
const data = res.body; // should be an object that needs to updated
transaction.update({_id: PreferanceMasterName._id}, data, {new: true }, ( error, obj ) => {
if( error ) {
console.error( JSON.stringify( error ) );
}
console.log( obj );
});
In certain cases new doesn't work, you can use : { returnOriginal: false };
for more details, you can check this thread there are multiple ways you can do this.
Please check update how to use it.
My document schema is as follows:
const CollectionSchema = mongoose.Schema({
ImageCategory:{type:String,required:true},
imgDetails: [
{
_id: false,
imageUrl:{type:String},
imageName:{type:String},
imageMimeType:{type:String},
}
],
Date: {
type: String,
default: `${year}-${month}-${day}`,
},
},{timestamps: true,})
So in the database for example one document has multiple images with a single image category. What I am trying to do is I want to delete an object from imgDetails array.
Let me explain my question more precisely: imgDetails is an array
Explanation: I want to loop in imgDetails and then find (where imgageUrl === req.body.imageUrl) if its match delete that whole object which have that req.body.imageUrl and then update the document.
Please guide me on how to write such a query. Regards
Demo - https://mongoplayground.net/p/qpl7lXbKAZE
Use $pull
The $pull operator removes from an existing array all instances of a value or values that match a specified condition.
db.collection.update(
{},
{ $pull: { "imgDetails": { imageUrl: "xyz" } } }
)
In Mongo, is it possible to increase and get the result of the increment?
collection.update({id: doc_id}, {$inc: {view_count: 1}});
I tried to output the result of that statement (in node) and I got the following:
{ _id: 1,
_state: undefined,
_result: undefined,
_subscribers: [] }
You can use findAndModify. Add the new:true option.
According to the docs:
The findAndModify command modifies and returns a single document. By default, the returned document does not include the modifications made on the update. To return the document with the modifications made on the update, use the new option.
You could do the following:
db.collection.findAndModify(
query: {_id: doc_id},
update: { $inc: { view_count :1 } },
new: true,
)
If you canĀ“t find the findAndModify method to use on your collection,you can use the findOneAndUpdate method.
Here is how to use:
The following code finds the first document where name : R. Stiles and increments the score by 5:
const result = await db.grades.findOneAndUpdate(
{ "name" : "R. Stiles" }, //also you can search for id
{ $inc: { "points" : 5 } }
)
The code returns the original document before the update inside the "value" propety:
{ _id: 6319, name: "R. Stiles", "points" : 0,... } // result.value returns document before update, but in the db it changued
If you want get the document uploaded, you has to set "returnNewDocument" to true, so the operation would return the updated document instead.
I hope it works for you.
source: https://www.mongodb.com/docs/manual/reference/method/db.collection.findOneAndUpdate/