Using variables in MongoDB update statement
You can do it this way:
'blur .editable' : function () {
var target = event.currentTarget.value;
var field = event.currentTarget.name;
var obj = {};
obj[field] = target;
Hostings.update( { _id: this._id },{ $set: obj } );
}
Javascrip objects can be accessed two ways:
object.attribute
or
object["attribute"]
if you use the second method you can access it with a variable
using a variable in mongodb update
You need to build up your $set
object programmatically:
var setModifier = { $set: {} };
setModifier.$set['directions.' + index + '.name'] = area.value;
Items.update(Session.get('selectedItem'), setModifier);
Update
If your JavaScript environment supports computed property names (e.g. node.js 4+), you can do this in one step:
Items.update(Session.get('selectedItem'), { $set: {
['directions.' + index + '.name']: area.value
}});
How to use variable while updating a mongo document?
You need to create an object where the value of foo
becomes the key, and pass that to the $set
operator.
var whatToSet = {};
var foo = 4; // or your number you want to store
whatToSet[foo] = {who: '3', txt: 'whatever', time: '2100'};
MNChats.update(
{_id: Session.get('activeConversationID')},
{ $set: whatToSet }
);
You may also want to revise this data structure to be an array, so you'll be able to use the $push operator.
update mongodb with node.js using a variable in $set
In javascript you cannot use variables as property names in object literals, and that's what you're trying to do.
Try it:
var a = 'someProperty';
var o = {a: 'somePropertyValue'};
console.log(o);
will print { a: 'somePropertyValue' }
not {someProperty:'somePropertyValue}
.
If javascript permitted referencing variables in property names in object literal notation it would have to get rid of unquoted names as those would create ambiguity.
Should a
be used as the value of the property or should it be the value of the variable a
?
Try creating the update object literal with an object crated beforehand without the usage of object literal notation, so your code looks something like this:
router.get('/vote/:Id/:Value/:Type', function(req, res) {
var db = req.db;
var id = req.params.Id;
var type = req.params.Type;
var value = parseInt(req.params.Value);
var newValue = value + 1;
var collection = db.get('games');
//We create the $set property/value pair using property assignment, not the object literal
var updateVal = {};
updateVal[type] = newValue;
collection.update(
{"_id" : id},
{$set: updateVal} //use it here
, function (err, doc) {
if (err) {
res.send("There was a problem");
}
else {
res.location("../../../admin");
res.redirect("../../../admin");
}
}
);
});
Even better, construct the whole $set
operation beforehand.
Update Mongo variable value with variable itself
The simple answer is: You cannot! You cannot update a field using another field. So you cannot update a field using itself. See also here.
BTW:
This
$set:{"name":"name" + " Is"}
will set the name
property to "name Is"
.
How can I use variables in an update operation in mongodb that involves an array or another type of embedded or nested document?
I think something like
var field = req.body.fieldName // japanese2
var task = req.body.question; // japanese2a
var updateObj = { $set : {} };
updateObj.$set[field + '.0.' + task] = 100
db
.collection("myCollection")
.updateOne({username:username}, updateObj);
Might work
Mongodb: updating a variable field name
You can use an intermediary object:
var update = { $set : {} };
update.$set['hello.' + newFieldName] = 'Amazing Grace';
db.bios.update({ _id : 3 }, update, ...)
Update Field with variable meteor mongo
First, you should reconsider the data structure you have. Having numbered keys is usually not recommended. It would be better in your case to use an Array of spots to get better benefits from mongo request engine.
The only case when you should keep your structure is if you are 100% certain not to need to have 4 spots per Town.
{
"_id" : "vK4PvdNBfBbdv92PH",
"ownerId" : "J8MpsWChPQdET6jwQ",
"createdAt" : ISODate("2018-07-04T07:25:28.406Z"),
"spots" : [
{
"name": "spot1",
"construction" : false,
"constructingBuildingName" : "",
"buildingName" : "factory",
"level" : 1,
"startTime" : 0,
"finishTime" : 0
},
{
"name": "spot2",
"construction" : false,
"constructingBuildingName" : "",
"buildingName" : "",
"level" : 0,
"startTime" : 0,
"finishTime" : 0
},
{
"name": "spot3",
"construction" : false,
"constructingBuildingName" : "",
"buildingName" : "",
"level" : 0,
"startTime" : 0,
"finishTime" : 0
}
]
}
Then,I advise you get a look inside the mongoDB documentation here. It explains how to do such an update using $elemMatch
'buildNewBuilding': function (userid, buildingid, spotnumber) {
var spotName = "spot" + spotnumber.toString();
var data = Buildings.find({_id: buildingid}).fetch();
var constructingBuildingName = data[0].name;
var startTime = Math.floor(Date.now() / 1000);
var finishTime = startTime + data[0].time;
Towns.update({ownerId: userid, spots: {$elemMatch: {name: spotName}}}, {$set: {
"spots.$.constructingBuildingName": constructingBuildingName,
"spots.$.startTime": startTime,
"spots.$.finishTime": finishTime,
"spots.$.construction": true,
}})
}
Related Topics
How to Use Command Line Arguments in Angularjs Protractor
Angular2 Dynamic Input Field Lose Focus When Input Changes
Sanitizing User Input Before Adding It to the Dom in JavaScript
Element Not Visible Error (Not Able to Click an Element)
Using Jquery to Find an Element at a Particular Position
Javascript: Uncaught Typeerror: Cannot Call Method 'Addeventlistener' of Null
Es6 Promise.All() Error Handle - Is .Settle() Needed
How to Get a JavaScript Object Property Name That Starts with a Number
Updating and Merging State Object Using React Usestate() Hook
Capture Value Out of Query String with Regex
What Are the Semantics of Different Rxjs Subjects
Is There Any Difference Between Declared and Defined Variable
Finding Closest Element Without Jquery
Destructuring and Rename Property
Difference and Intersection of Two Arrays Containing Objects
Event Delegation VS Direct Binding When Adding Complex Elements to a Page