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

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.

Related

Pull a full object from one value

I'm working on a ticket system, and I want to make a close ticket system, that will remove the ticket from the user, so I have my mongo array looking like this
{
"tickets": [{
"id": "cxZgqey2",
"subject": "fdgfdgdfgfdgfd",
"message": "gfdgfdgfdgdfg",
"ownerEmail": "soenmtherhg#gmail.com"
},
{
"id": "r4r-CnIC",
"subject": "dfdsfdsfsdfdsfdsf",
"message": "dsfdsfdfsdfdsfdsfdsfdsf",
"ownerEmail": "soenmtherhg#gmail.com"
}
]}
and I wanted to remove the entire object using only the id, how would I do this? (Using the npm module (not mongoose))
You can use the filter function in arrays and delete it passing the relevant id for that and also you can check loadash.

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.

Get all doc data from Cloudant as opposed to id, key, value

Trying to query against my db to get all docs with all info. The db.list functionality gets the overview of the docs but does not return all the data for the docs. Currently have to get the high level data then loop through the rows and query each individual doc. There must be a better way...
Is there a way to get all docs with the full set of info for each doc?
getting:
{
"id": "0014ee0d-7551-4639-85ef-778f74365d05",
"key": "0014ee0d-7551-4639-85ef-778f74365d05",
"value": {
"rev": "59-4f01f89e12c488ba5b8aba4643982c45"
}
}
want:
{
"_id": "14fb92ad75b8694c05b98d89de6e9b2d",
"_rev": "1-6067c00b37a18ad8bab6744d258e6439",
"offeringId": "ae0146696d1d3a90fe400cc55a97a60e",
"timestamp": 1464165870848,
"srcUrl": "",
"score": 9,
...
}
The repository you linked to for nano looks like an outdated mirror. The official repository includes documentation for db.list which also includes a params object. I would double-check your version of nano, but I would guess you already have a more recent version.
You can simply add { include_docs: true } as the first argument to db.list and alongside id, key and value, you'll get a doc property that has the entire document.

Meteor.js update only one parameter instead of whole collection

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.

ID value in Facebook Comments.Create callback

According to the Facebook documentation, the comment.create callback contains a Comment ID property:
{
href: "", /* Open Graph URL of the Comment Plugin */
commentID: "", /* The commentID of the new comment */
}
However I'm seeing that the callback contains a common ID property that doesn't change across the comments. For example, when i debug the callback I get an commentID value of "10150259852273822", but the value doesn't change for any comment left on that page. Below is a sample for the comments from the Graph API, notice the ID is the same across multiple comments, but its appended by a "_XXXX" number that appears to actually be the identifier.
{
"id": "10150259852273822_17973898",
"from": {
"name": "XXXXXX",
"id": "XXXXX"
},
"message": "newest comment",
"created_time": "2011-08-24T19:24:02+0000"
},
{
"id": "**10150259852273822**_17973932",
"from": {
"name": "XXXXX",
"id": "XXXXX"
},
"message": "brand newest comment.",
"created_time": "2011-08-24T19:25:40+0000"
}
Does anyone know how you can actually get the full identifier via the comment.create event? Or is there another field that can be used to predict the commonid_commentID format?
The comment ID from the callback is in fact the "post_fbid".
Here is how you can get the comment (and the data associated with it) :
FB.Event.subscribe('comment.create', function(response) {
var commentQuery = FB.Data.query("SELECT text, fromid FROM comment WHERE post_fbid='"+response.commentID+"' AND object_id IN (SELECT comments_fbid FROM link_stat WHERE url='"+response.href+"')");
var userQuery = FB.Data.query("SELECT name, uid FROM user WHERE uid in (select fromid from {0})", commentQuery);
FB.Data.waitOn([commentQuery, userQuery], function() {
// Do whatever you want with the data
console.log(commentQuery.value[0].text);
console.log(userQuery.value[0].name)
console.log(userQuery.value[0].uid);
});
});
What do you need/want the ID for. Perhaps we can come up with a better solution for what you need.
The common ID element is most likely (off the top of my head) specific to that comment form. And the additional bit is the "true" id of the comment as it were.
The full identifier of the comment is the whole element, your number that doesn't change and the appended element post the underscore.
Take a look here: http://developers.facebook.com/docs/reference/api/Comment/
And at the example graph URL.
The full string included underscored element is fully part of the comment ID

Categories

Resources