How do I use jQuery's .get() method with MongoDB - javascript

I'm a complete MongoDB beginner and I'm wondering how jQuery's .get() method works. I've been able to use .post() to add and update items in the DB, and that jQuery looked like this:
$.post(document.URL, {'answers':answer})
Now I'm trying to get information to the client side first using the following find() method, which successfully retrieves the correct information and logs it into terminal.
this.find(query, {"answers":"true", "blanks":"true"}, function(err, doc){
console.log("The correct info appears in terminal: "+doc); //{_id:52a52ee1e80e7c0000000001, answers: [ 'more', 'One', 'more' ], blanks: ['try']}
return doc;
callback();
});
Than I'm trying to send that same info to the client-side with this jquery, but it only logs the html on that page, and not the desired 2 arrays from mongo.
$.get(document.URL, {'answers':[], 'blanks':[]}, function( doc ) {
console.log( doc ); //This is all the html on my page
});
How do I .get() the 2 arrays?

Related

How can I get a value from youtube api?

I'm building a chatbot that retrieves a youtube link based on what the user has asked.
I'm using Dialogflow for the bot and using nodejs for the coding.
Right now, everything works perfectly but my problem is retrieving the link from the API response.
using console.dir(results), shows the following:
This is how the response looks like:
[ { id: 'gWNUg_v25dw',
link: 'https://www.youtube.com/watch?v=gWNUg_v25dw',
kind: 'youtube#video',
publishedAt: '2017-08-24T14:00:11.000Z',
channelId: 'UCDZ56yQ05d_ikcwcTG9bAiA',
channelTitle: 'Code to Create',
title: 'How to make a Chatbot with Dialogflow - API.ai',
description: 'In this video, Google Developer Expert, Faisal Abid will show us how to create a chatbot with Google\'s latest API.ai API.ai can be integrated with multiple chat ...',
thumbnails: { default: [Object], medium: [Object], high: [Object] } } ]
I have tried using results.link to retrieve the link but Im getting undefined, so my question is how to retrieve the link from the response block?
search(txt1, opts, function(err, results) {
//var data1 = JSON.parse(results);
//srchRes = data1.link;
if(err) return console.log(err);
console.dir(results);
});
uncommenting the 2 lines above and console.dir(srchRes) returns this error:
SyntaxError: Unexpected token u in JSON at position 0
We don't have your API call code logic so from here, we could only assume results is the API's response and given your exemple about how the response look like, then we see results is an array of object.
JSON.parse actually deserialize a string which represent an object given the JSON format.
JSON.stringify is the contrary, it serialize your object to a string with the JSON format.
Your goal is to reach the link properties of a particular object within the array, which is why JSON.parse(results) makes no sense.
You should be able to reach linkproperties for each object by simply iterate over the array of object results
for (const result of results) {
console.log(`the link : ${result.link}`)
}

I am unable to retrieve data from my mongodb collection and show it to my html page [duplicate]

I have a publication that should return me all users matching an _id array. here it the query:
Meteor.users.find({
'_id': { $in: myArray}},{
'profile.name':1,
'profile.description':1,
'profile.picture':1,
'profile.website':1,
'profile.country':1}
);
When I run it in Robomongo (the mongo browser), it works. But my publication only returns undefined. when I console.log(myArray); in the publication, I get something like this ['FZ78Pr82JPz66Gc3p']. This is what I paste in my working Robomongo query.
Alternative question: how can I have a better feedback(log) from the Collection.find() result?
It looks like you are trying to specify fields in your find, which you can do like this:
var options = {
fields: {
'profile.name': 1,
'profile.description': 1,
'profile.picture': 1,
'profile.website': 1,
'profile.country': 1
}
};
Meteor.users.find({_id: {$in: myArray}}, options);
However, if this is being used in a publish function, I strongly recommend using only top-level fields like so:
Meteor.users.find({_id: {$in: myArray}}, {fields: {profile: 1}});
For more details on why, please see this question.
For your second question, you can view the documents returned by a cursor by calling fetch on it. For example:
console.log(Posts.find({_id: {$in: postIds}}).fetch());

Write an object containing an array of objects to a mongo database in Meteor

In my user collection, I have an object that contains an array of contacts.
The object definition is below.
How can this entire object, with the full array of contacts, be written to the user database in Meteor from the server, ideally in a single command?
I have spent considerable time reading the mongo docs and meteor docs, but can't get this to work.
I have also tried a large number of different commands and approaches using both the whole object and iterating through the component parts to try to achieve this, unsuccessfully. Here is an (unsuccessful) example that attempts to write the entire contacts object using $set:
Meteor.users.update({ _id: this.userId }, {$set: { 'Contacts': contacts}});
Thank you.
Object definition (this is a field within the user collection):
"Contacts" : {
"contactInfo" : [
{
"phoneMobile" : "1234567890",
"lastName" : "Johnny"
"firstName" : "Appleseed"
}
]
}
This update should absolutely work. What I suspect is happening is that you're not publishing the Contacts data back to the client because Meteor doesn't publish every key in the current user document automatically. So your update is working and saving data to mongo but you're not seeing it back on the client. You can check this by doing meteor mongo on the command line then inspecting the user document in question.
Try:
server:
Meteor.publish('me',function(){
if (this.userId) return Meteor.users.find(this.userId, { fields: { profile: 1, Contacts: 1 }});
this.ready();
});
client:
Meteor.subscribe('me');
The command above is correct. The issue is schema verification. Simple Schema was defeating the ability to write to the database while running 'in the background'. It doesn't produce an error, it just fails to produce the expected outcome.

Azure documentdb stored procedure returning partial result

Currently I have got given stored procedure
function getData() {
var context = getContext();
var collection = context.getCollection();
var output = collection.map(function (doc) {
return {
id: doc.id,
name: doc.name,
status: doc.status,
description: doc.description,
owner: doc.owner
}
})
return JSON.stringify(output)
}
Issue here is that it only returs 7 documents (matching what you get when you not get 'load' action on azure panel) and is skipping rest of the collection.
I believe that it can be fixed with using SQL query syntaxt but I would like to know how can I query all documents in the collection without using it.
Try adding a FeedCallback like shown here and make the signature of the callback be function(error, resources, options). Look for errors. Also inspect the options parameter for a continuation. If that fails to give you enough information to fix the problem, then you might want to consider a more traditional query and transformation approach not using collection.map().

The new:true option returns me the old value in MongoDB

I'm using the following code in MongoDB v2.2 NodeJS 0.8 MongoSkin 0.5 Framework:
var db = mongo.db(admin+"#127.0.0.1:27017/database",{safe:true});
db.collection('collection').findAndModify({'code':code,'email':email},[],
{
$push:
{
'code.pub':newPub,
}
},{new:true},
function(err, result)
The new true option returns me the old value in MongoDB. Why is this happening? What is wrong?
set {w: 1} or, {safe: true} which is deprecated.
in your query you search for: "{'code':code,..." and in the update you say "$push: {code.pub...
If your "code" field contains an object (sub-document) - your query will not find anything and the update will fail
Could you please post the complete statement (with the content of the variables) and an example of the document being updated?
Cheers
Ronald

Categories