If I do the following search:
VideoCourses.find({'_id': 'jkwehrjewrew'}).fetch()[0].videos
I get the following:
Object {first: "firstvideo.html", second: "secondvideo.html", third: "thirdvideo.html"}
My question, is how can iterate through the collection. I want to render one video at a time, so I can render the first video, and then on click, render the second, etc.
The thing is, I have many sets of videos, so this should be done dynamically. It should iterate through the next video.first, video.second.. etc.
Is that possible? I've looked into .next() but I think that works for an entire collection, not an object inside the collection.
Thank you in advance!
This is a JavaScript question, not necessarily Meteor. Use a for-in loop to iterate through objects.
// This query returns an object
var MyObject = VideoCourses.find({'_id': 'jkwehrjewrew'}).fetch()[0].videos
// The object is brings back looks like this:
// {
// first: "firstvideo.html",
// second: "secondvideo.html",
// third: "thirdvideo.html"
// };
// Use a for-in loop to iterate through the object
for(key in myObject){
console.log("this is the key: ", key, ", and this is the value: ", myObject[key]);
};
Related
Why dosen't db.find work? The console.log gets undefined...
var course = (db.courses.find({ _id: mongo.helper.toObjectID(param.course)}));
console.log(course.body)
The way you are trying use Selects documents in a collection and returns a cursor to the selected documents., so you can't use the way you are trying to use it.
You need to use a callback() to get the records matching the query.
The below code will give result in an array format :-
db.courses.findOne({ _id: mongo.helper.toObjectID(param.course)}).toArray(function(err, result)
{
console.log(result[0]); // will give you the matched record.
})
Alright, so I have a collection called Polls. Inside the Polls "table" there is an attribute called choiceObjects which is an array of objects. Each object inside this array has its own attributes. What I need to do is update one of the attributes there. Ill give you a screen shot so you can better visualise what Im talking about
As you can see the choice objects have attributes like body, country etc. There is another attribute called pollid which is set to optional and therefore you cant see it right now. I need to update this pollid attribute now that I have acess to the pollid
Polls.update(
{ _id: pollId },
{ "$set": { "choiceObjects": { pollid: pollId } } }
); //this is kind of what Im trying to do but this isnt right
Since then... I have further tried the following :
var selectedpoll = Polls.findOne(pollId);
console.log(selectedpoll);
//Polls.update( selectedpoll, {"$set"{'choiceObjects.$.pollId':pollId}},false, true );
but when i try that i get the error : the positional operator did not find the match needed from the query. unexpanded update: choiceObjects.$.pollId
If I understand your objective correctly, you want to update (or add) pollid to all objects in the choiceObjects array. Unfortunately $, $push, $addToSet only work with single elements AFAIK.
This might not be what you are looking for but one possible and very obvious way to approach this problem would be to update the entire array in the collection i.e.
var choiceObjects = Polls.findOne({_id: pollId}).choiceObjects;
for (var i = 0; i < choiceObjects.length; i++) {
choiceObjects[i].pollid = pollid;
}
Polls.update({_id: pollid}, {choiceObjects: choiceObjects});
I am trying to do something like this:
Industry.findOne({_id: id}).exec(function(err, industry){
industry.stats = _.extend(industry.stats, stats); //.......(1)
industry.save(function(err) {
// nothing is saved
});
});
The console.log of industry.stats in (1) is
[{ stat_id: 545080c8e4e88b1d5a7a6d1b}{ stat_id: 54526ca6b294096d33ca6b36 }]
This is not working, apparently the industry.stats is not an object array and misses a comma in between the two objects. (am I stating this correctly?)
If I assign industry.stats directly like this
[{stat_id: 545080c8e4e88b1d5a7a6d1b}, {stat_id: 54526ca6b294096d33ca6b36}]
Then it's working. Is there something I need to do to convert (1) to an object array first? I tried lean() and toObject()...etc but I got no luck. Am I missing something?
Lodash extend will assign own enumerable properties of source object to the destination object. In this case array properties of the source (stats) are copied to industry.stats. This will not work for arrays.
You'll have to update the array via array functions (push, pull,...) or set the field directly.
I'm wondering the best way to query mongo db for many objects, where each one has an array of _id's that are attached to it. I want to grab the referenced objects as well. The objects' schemas looks like this:
var headlineSchema = new Schema({
title : String,
source : String,
edits : Array // list of edits, stored as an array of _id's
...
});
...and the one that's referenced, if needed:
var messageSchema = new Schema({
message : String,
user : String,
headlineID : ObjectId // also contains a ref. back to headline it's incl. in
...
});
One part of the problem (well, depending if I want to keep going this route) is that pushing the message id's is not working (edits remains an empty array [] afterwards) :
db.headline.update({_id : headlineid}, {$push: {edits : messageid} }, true);
When I do my query, I need to grab about 30 'headlines' at a time, and each one could contain references to up to 20 or 30 'messages'. My question is, what is the best way to fetch all of these things? I know mongo isn't a relational db, so what I'm intending is to first grab the headlines that I need, and then loop through all 30 of them to grab any attached messages.
db.headline.find({'date': {$gte: start, $lt: end} }, function (err, docs) {
if(err) { console.log(err.message); }
if(docs) {
docs.forEach(function(doc){
doc.edits.forEach(function(ed){
db.messages.find({_id:ed}, function (err, msg) {
// save stuff
});
});
});
}
});
This just seems wrong, but I'm unsure how else to proceed. Should I even bother with keeping an array of attached messages? I'm not married to the way I've set up my schema, either. If there is a better way to track relationships between them, or a better query to achieve this, please let me know.
Thanks
Does each message belong to only one headline? If so, you can store the headline id as part of each message. Then for each headline, do:
db.messages.find({headline_id: current-headline-id-here})
You could try using the $in operator for selecting a list of ObjectIds
http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24in
I made a simple db with a few users in it with mongodb and nodejs. Next im looping through the list and display the users in the list's names etc with sys.puts().
No I am adding the users to an Array() like this:
db.open(function(err, db) {
db.collection('users', function(err, collection) {
collection.find({}, {'sort':[['name', 1]]}, function(err, cursor) {
cursor.each(function(err, user) {
if(user != null) {
users[user._id] = { 'name':user.name, 'email': user.email };
sys.puts(">> Adding user to list... "+ user.name);
}
});
db.close();
});
});
});
Is this how I add the users to the array? Because the users.lenght = 0. Im a bit lost now
What you are doing is setting properties on the array object, that might be a bit confusing.
[] is both used for indexes and keys, that means in case of your array, users[0] will return the first element in the array, but users['blaid12'] will get/set the property blaid12' on the array object, that's like doingusers.blaid12`.
So in the end your array becomes more like a hashmap. The length property does not count the properties of the object, it counts the elements in the array.
You have a couple of ways of solving the issue:
Use an object {} and use the user ids as keys on that object, you'll have to keep track of the user count via another variable.
Use the array as an array by using users.push({'name':...}) to append elements to the array, if you need the userid too, then just add it to the object you push into the array.
Go with a mixed approach, use an array to push the values, and then an object to map the ids to the array indexes.