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

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());

Related

How to get all records from collection using createddate field in meteor js application

I have a sample transactions collection similar to below
[
{"_id":"123","createddate":"2017-07-24T09:43:31.028Z"},
{"_id":"124","createddate":"2017-07-25T09:43:31.028Z"},
{"_id":"125","createddate":"2017-07-26T09:43:31.028Z"},
{"_id":"123","createddate":"2017-07-28T09:43:31.028Z"},
{"_id":"126","createddate":"2017-07-27T09:43:31.028Z"}
]
But in my production we have around 50-60 records for each date(createddata field).I need to get all the records for a particular date based on selection then download that.
I used below:
Meteor.methods({
gettransactionsdata:function(){
let transactionRecord = transactions.find({"createddate":"2017-07-26"});
return transactionRecord;
}
});
When I try calling above function it is returning transactionRecord as undefined. How can we do this?
You're storing dates as strings instead of dates which is not recommended for numerous reasons. For a simple day you can do a $regex search to find the strings that begin with the day you're looking for:
transactions.find({ createddate: { $regex: /^2017-07-26/ }});
You could also just pass that date string to your method for a bit more flexibility:
Meteor.methods({
gettransactionsdata(dateStr) {
return transactions.find({ createddate: { $regex: new RegExp('^'+dateStr) }});
}
});

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.

Find Value in Meteor Mongo

I am new to web programming and have recently been playing around with Meteor and MongoDB.
I have a form which sends data to mongo and using the query below have retrieved the most recently entered value:
database.findOne({}, {sort: {'timeStamp' : -1}, limit:1})
Which is cool however, I only want the value of a specific variable not the entire entry so I can use that variable with calculations elsewhere.
Does anyone have an pro tips? Should I use distinct()?
Thanks!
If you are looking to retrieve a field out of the returned document, you can specify as much using the fields option:
database.findOne({}, {sort: {'timeStamp' : -1}, limit:1, fields: {'myField': 1, _id: 0})
That will retrieve an object in format like this:
{'myField': 'value of myField'}
So if you want to interact directly with that you can access it like so:
var myVar = database.findOne({}, {sort: {'timeStamp' : -1}, limit:1, fields: {'myField': 1, _id: 0}).myField
As a more concrete example, I have a user database with username, name, _id, etc., and if I just want to store a user's name in another variable, I can do so like this:
> a = Meteor.users.findOne({}, {fields: {name: 1, _id: 0}}).name;
> a
<- "Bob" // returned "Bob"
Note that if you want to pull the data for a specific ID or other selector, you'll need to fill that in in the selector:
database.findOne({_id: "myId"}, ...)
See the Meteor Mongo.Collection.find documentation for more information.

Sails.js query on an associated value

I'm using Sails.js version 0.10.0-rc4. All models are using sails-mysql.
I'm trying to query a model which has an "one-to-many" association to another model (the query is happening on the "many" side).
It looks something like this:
Post.find()
.where({ category: category_id })
.populate("category")
.exec( ... )
This gives me an empty array back however when I leave out the .populate("category") I get the correct result set.
I know that I could leave .populate("category") out and then fetch each correlating Category object separately, but I'm wondering if there's a better solution to this problem.
It's not 100% clear what you're trying to do here. If your goal is to filter the categories that get populated on the Post, you can do:
Post.find()
.populate("category", {where: { category: category_id }})
.exec( ... )
If you want to only retrieve Posts with a certain category, you would do:
Category.findOne(category_id)
.populate("posts")
.exec(function(e, c) {console.log(c.posts);})
Original post was too soon
Following works for me (sails 0.12) with population:
Post.find({category: category_id})
.populate("category")
.exec( ... )
But I am still puzzled who to search in a subquery any other attribute than id..
Edit2: Seems like deep query is not yet supported: https://github.com/balderdashy/waterline/issues/266

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

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?

Categories