Meteor.js update only one parameter instead of whole collection - javascript

I'm trying to mark message as readed using code below :
Template.FullMessage.onRendered(function () {
var id = FlowRouter.getParam('id');
Messages.update(id, {$set: {readed: true} });
});
Collection is :
"_id": "YMxYn9NodPeZqFP83",
"whatAbout": "adsfadsfasdf",
"message": "sdfadsfadfadsfasdfasdf",
"recipientId": "9ewiF8JTNp77Pmijw",
"author": "9ewiF8JTNp77Pmijw",
"createdAt": "2016-05-09T08:37:52.282Z",
"owner": "seofilms",
"readed": false
}
I expected that column "readed":"false" will be replaced with "readed":true,
but instead of it, everything in here is changing, including owner. So for instance if I will open message with user test, I will change also the owner of this message.
Why does it happens ?
Is it possible to prevent sending whole object and change it only with ID?
Thank you for any ideas.

Try this:
Messages.update({_id: id}, {$set: {readed: true} });
It should also work with only id, as you're already doing. Is there any other code that's writing to the same collection? Try to run it in console and check if it's still updating all the properties.

Related

Node - Mongoose update method issue

I need to update and already queried document:
In memory save way works fine:
project.likers.push(profile.id);
project.set({
likes: project.likes + 1
})
await project.save();
But I read in a blog that this way is slower as compared to using mongoose update method.
Since I am using multiple queries in this endpoint, I want to use mongoose update method for the same reason.
Doesn't work
project.update({ "$push": { "likers": profile.id }, "$inc": { "likes": 1 } });
Thanks in advance!
$push : The operator appends a specified value to an array.
And there isn't command 'update'. There are two command for update and they are :
updateOne
updateMany
If you just want to update the existing field, you can use like below:
db.collectionname.updateMany({ "likers": profile.id }, { "$inc": { "likes": 1 } })
If you want more info, check out.

Only update mongo document if value is bigger

I got a collection of documents in mongo DB.
One of the fields in the document is "verison" : int
I was wondering if there is a practical way to use this value to prevent update of the document when there is an attempt to update it with the same or smaller version number.
example :
my collection has a document :
{
"name": "john",
"version": 3
}
if I try to send update with :
{
"name": "rick"
"version": 3
}
It wont update it, and I will get an indication that there was no update so I can handle this in some way in my code.
I am using node.js with native mongo DB driver.
You can solve using the below Code.
db.collection.update({'version':{$gte : 3}},{$set : {name:'Abc'}},{upsert : true,new:true})

Firebase returns the entire database even with setting ref url

I am trying to setup Firebase's realtime database in my web app.
I have everything initialized properly and can connect to the database. However, when I try to fetch data, I get the entire database returned in the snapchat.
The code I have here is trying to determine if a key exists:
var ref = firebase.database().ref('cars/');
ref.once('value', function (snapshot) {
if (snapshot.hasChild('toyota')) {
alert('exists');
} else {
alert('does not exist');
}
});
This always displays the 'does not exist' dialog, so when I ran:
alert(JSON.stringify(snapshot));
I realized that firebase was fetching everything.
Here is the structure of my database:
{
"users": {
"uid": {
"name": "John Doe",
"balance": 500
}
},
"cars": {
"carid": {
"name": "Name of Car",
"cost": "250",
"features": [
"ac", "awd", "leather_seats"
]
}
}
}
Does anybody know how to fix this? Every request I make just returns the entire database, which is frustrating. Thanks.
Hey try using the child method to access your nodes
var ref = firebase.database().ref().child('/cars');
Sorry there was some missing bits.
I retrieve data for a node in the following way, without the preceding or trailing slash. Check if the following works.
var ref = firebase.database().ref().child('cars');
For some reason firebase had an entire duplicate of the database placed under the node, so in actuality I was fetching the data from the specific node, it just so happened that it contained a copy of the database.
What I'm curious about is to how this could happen, as I was under the impression that when you imported JSON into firebase, it overwrote the entire database.

MongoDb: Find the generated id of the inserted child on parent save

If I have a document representing a post with comments that looks like this:
{
"_id": "579a2a71f7b5455c28a7abcb",
"title": "post 1",
"link": "www.link1.com",
"__v": 0,
"comments": [
{
"author": "Andy",
"body": "Wish I had thought of that",
"_id": "579a2a71f7b5455c28a7abcd",
"upvotes": 0
},
{
"author": "Jim",
"body": "Just a comment",
"_id": "579a2a71f7b5455c28a7abcc",
"upvotes": 0
}
],
"upvotes": 5
}
In the calling (javascript) code, I add a new comment, by pushing to the post.comments array, then save the post using .save with a callback. In the save callback, I want to get the generated _id of the new comment I just saved. How do I do this?
I've got the parent post document in the callback, of course, but that's not useful as I can't tell which comment was just inserted.
Is there another document method or an alternate form of the .save callback to deal with my situation?
Or do I have to just follow what I'd usually do and generate a unique id on the comment myself before the save?
EDITED: I'm using Mongoose, sorry, forgot to say!
You did not specifically tell, but I assume you use Mongoose because standard MongoDB will not add an _id property to subdocuments.
As mentioned in the Mongoose documentation regarding adding sub-documents, you can use the following code example:
var Parent = mongoose.model('Parent');
var parent = new Parent;
// create a comment
parent.children.push({ name: 'Liesl' });
var subdoc = parent.children[0];
console.log(subdoc) // { _id: '501d86090d371bab2c0341c5', name: 'Liesl' }
subdoc.isNew; // true
parent.save(function (err) {
if (err) return handleError(err)
console.log('Success!');
});
Instead of parent.children[0] you have to use parent.children[parent.children.length - 1] to access the inserted element, though.
I'd assume the item you pushed on the array would be the last one, but that wouldn't work in a multi user system.
Also you could make a comparison against the author and comment fields, though this seems like a lot of trouble, and with just the author and the comment text, you might not be assured a match.
Finally, you could also create the object id and assign it to the comment, then save it. You do that like this:
var mongoose = require('mongoose');
var id = mongoose.Types.ObjectId();
That's what I would do.

JavaScript JSON Parse Issue ($.getJSON)

I can't seem to get the following code to output anything to the screen. JavaScript is not my strong suit!
This is the JavaScript code calling a local file that outputs a list of rooms
$.getJSON('roomupdate.php?level=1&div=1&callback=json',function(res){
console.log(res.rooms.name[0]);
});
In the above I'm merely trying to see the name of the first room in the console. And this is the JSON output (Which I can confirm the script can see and load)
json(
{
"rooms":
[
{ "name" : "Bedroom" },
{ "name" : "Living Room" },
{ "name" : "Lounge" },
{ "name" : "Kitchen" }
]
})
Could anyone suggest what I am doing wrong? Even to view in the console?
Lastly, can you loop through the array?
Your JSON data contains an object rooms and this object actually contains an array [], So to access the data inside your array you need to put the index on rooms :
console.log(res.rooms[0].name);
Use callback=? rather than callback=json so that jQuery knows you are using JSONp and can choose it's own name for the callback function.
$.getJSON('roomupdate.php?level=1&div=1&callback=?',function(res){
//alert('Your name is '+res.rooms);
console.log(res.rooms.name[0]);
});
See http://api.jquery.com/jQuery.getJSON/#jsonp for details.
Edit:
Looking again, you will need to change the way you are accessing the data around. res.rooms.name[0] should be res.rooms[0].name because rooms is a list, and each room has a name property.
This will loop through the array of rooms and log the name of each one:
$.each( res.rooms, function( i, room ) {
console.log( room.name );
});
If that doesn't work, then add this statement at the beginning of your callback (where you have the console.log() call now):
debugger;
Load/run your page with the developer tools open, and it will stop in the debugger where you have that statement. Now you can look at all your variables in detail, try out expressions to see what they do, single step through your code, etc.

Categories

Resources