Menu
  • HOME
  • TAGS

add subitems to meteor document

Tag: mongodb,meteor,collections,insert-update

I have a meteor collection "list" that has the following data structure.

   "list" : [
  {
     "_id" : "id",
     "author" : "authorId",
     "createdOn" : "DateTime",
     "description" : "description",
     "items" : [
        {
           "item1" : {
              "itemComplete" : "Boolean",
              "itemName" : "item name",
              "itemDescription" : "item description",
           }
        },
        {
           "item2" : {
              "itemComplete" : "Boolean",
              "itemName" : "item name",
              "itemDescription" : "item description",
           }
        }
     ],

Users will be able to add arbitrary number of list items. I am trying to figure out how to add itemX programmatically. E.g. I have the following code (which does not work) that gives an idea of what I am trying to accomplish.

 var currentItemCount = Lists.find({_id:_currentListId, items:{}}).count() + 1;
 var newItemNum = "item" + currentItemCount;
 var newListItem = $("#list-item").val(); 
 Lists.update({_id:_currentListId},{$push : {items:{newItemNum:{itemName:newListItem}}}});

I would appreciate any suggestions or hints to help me fix my code. Please let me know if I am missing some information.

Thanks in advance.

Kamal

Best How To :

Give something like this a try:

// fetch the current list
var list = Lists.findOne(_currentListId);

// find the number of existing items and handle the case where there are none
var numItems = (list.items || []).length;

// the the next item key will be one more than the length
var itemKey = 'item' + (numItems + 1);

// extract the item name from a form
var itemValue = {itemName: $('#list-item').val()};

// you can't use varaiable names as keys in object literals
// so we have to use bracket notation
item = {};
item[itemKey] = itemValue;

// push the new item onto the list of items
Lists.update(_currentListId, {$push: {items: item}});

Incorrect response to mapReduce query in mongo-db

mongodb,mapreduce

Your problem here is that you have missed one of the core concepts of how mapReduce works. The relevant documentation that explains this is found here: MongoDB can invoke the reduce function more than once for the same key. In this case, the previous output from the reduce function for...

XMLHttpRequest to Restivus API

javascript,meteor,xmlhttprequest,cross-domain,cors

The answer is more than obvious after finding out. I just need to to set the options method in the restivus route to authRequired: false. You cannot send a complete header with credentials when doing a preflight. Now I am first doing the preflight and then sending the real post.

push item in sub document

mongodb,mongodb-query

You need the positional $ operator in your update portion of the statement: db.getCollection('forms').update( { "_id" : ObjectId("557e8c93a6df1a22041e0879"), "Questions._id" : ObjectId("557e8c9fa6df1a22041e087b") }, { "$push" : { "Questions.$.DataSource" : { "_id" : ObjectId("557e8e5ea6df1a27b403ff6b"), "CreationDate" : ISODate("2015-06-15T08:35:42.923Z"), "IsActive" : true, "Text" : "op", "Value" : "op" } } } ) It identifies...

Find Mongoid geospacial circles that contain a point

mongodb,mongoid,geospatial

Modelling a "circle" is a valid approach by specifying a "centre" and a "radius", but finding things "within the circle" is generally straightforward if not immediately obvious: Service.collection.aggregate([ # Get the distance from the current location { "$geoNear" => { "near" => { "type" => "Point", "coordinates" => [ 1,...

Meteor - Requests randomly failing

meteor,request-cancelling

Finally found the source of my problem maybe my answer would help other Meteor developers. I used to do this : var providersSub = Meteor.subscribe('providers'); Tracker.autorun(function () { if(!providersSub.ready()) return; var providerIds = _.pluck(Provider.all().fetch(), '_id')); ... this.stop(); }); Instead of : var providersSub = Meteor.subscribe('providers'); Tracker.autorun(function (computation) { if(!providersSub.ready()) return;...

Is there a built-in function to get all unique values in an array field, across all records?

arrays,node.js,mongodb,mongoose,schema

You can use the distinct function to get the unique values across all category array fields of all documents: Article.distinct('category', function(err, categories) { // categories is an array of the unique category values }); Put an index on category for best performance....

Are the changes done by db command in MongoDB permanent and how?

mongodb,mongodb-query

Yes, Changes made to data in MongoDB shell are permanent but for configuration parameters, they will last only till next restart of instance if they are not specified in config file. MongoDB runs with default values if config file is not specified. You can specify config file as, mongod --config...

CKeditor outputs Html. How to format it for displaying properly, not just lame html?

javascript,html,css,meteor,ckeditor

You use triple braces in spacebars for this. So your answer is {{{body}}} ...

How to overwrite object Id's in Mongo db while creating an App in Sails

mongodb,sails-mongo

Attention: Mongo id should be unique as possible in order to scale well. The default ObjectId is consist of a timestamp, machine ID, process ID and a random incrementing value. Leaving it with only the latter would make it collision prone. However, sometimes you badly want to prettify the never-ending...

Query not working - MongoDB

mongodb

Looks like you've missed some brackets before $elemMatch: db.items.find( { "$or": [ {"f": {$elemMatch: {"t": "ry", "v": {$gt: 1980}}}}, {"f": {$elemMatch: {"t": "g", "v": {$in: ["Drama"]}}}} ] } ) ...

Meteor: Passing Session values from client to server

javascript,node.js,session,meteor

I don't really understand your need. Why do you want to share Session with Server ? Session is client-side only, but you can send value if your session with Meteor Methods, or in your subscription. In the second case, your sbscription can be reactive with the Session dependancy. Could you...

How to return value in Meteor.JS from HTTP.call “GET”

javascript,ajax,http,meteor,facebook-javascript-sdk

Don't pass a callback to get the HTTP to return. You're also able to pass off URL parameters quite easily: var result = HTTP.call("GET", "https://graph.facebook.com/me", { params: { access_token : Meteor.user().services.facebook.accessToken, fields : "likes.limit(5){events{picture,cover,place,name,attending_count}}" } }); console.log(result); ...

MongoJS - No Error On Unique Index

mongodb,mongojs

This seems to be a "buggy" response from mongojs which likely results from it's implementation of returning the "inserted" object as a response. The "core" driver does not do this but would either return a "ok" response or an error: var MongoClient = require('mongodb').MongoClient; MongoClient.connect('mongodb://localhost/test', function(err,db) { var collection =...

Do you get the same performance using index prefixes?

performance,mongodb,indexing

A "compound index" which is the correct term for your "link" does not create any performance problems on "read" ( since writing new entries is obviously more information ) than an index just on the single field used in the query. With one exception. If you use a "multi-Key" index...

How to add new items to an array in MongoDB

arrays,node.js,mongodb

$set is not an array update operation. The $set operator replaces the value of a field with the specified value. You just want to use $push by itself, as in .update({_id: id}, {$push: {name: item}}) You can't interpolate object property names in raw object declarations, so if you want to...

How could I get the matched nested items in array

mongodb

You should first $unwind records and then match elements like following: db.collection.aggregate({ "$unwind": "$records" }, { "$match": { "records.items": { "$in": ["A428 ", "A429 "] } } }, { "$group": { "_id": "$_id", "records": { "$push": "$records" } } }).pretty() ...

Meteor collections: how to connect to different collections referring to each other?

meteor,meteor-helper,meteor-collections

You might be better off using Contracts._id to refer to a contract from the Reminders collection that way if the contract name and description change at some point you won't need to update all the related reminders. Contract: { "_id": "tPN5jopkzLDbGypBu", "contract": "C-42432432", "description": "Description of contract", "counterpart": "Company name",...

Query with filter builder on nested array using MongoDB C# driver

c#,mongodb,mongodb-query,mongodb-csharp,mongodb-csharp-2.0

The query you need to perform uses the $elemMatch query operator. So, this query using a lambda expression var findFluent = collection.Find(f => f.Bars.Any(fb => fb.BarId == "123")); Is equivalent to this query using the FilterDefinitionBuilder: var findFluent = collection.Find(Builders<Foo>.Filter.ElemMatch( foo => foo.Bars, foobar => foobar.BarId == "123")); ...

Inserting a variable in MongoDB specifying _id field

python,mongodb,pymongo

Insert only accepts a final document or an array of documents, and an optional object which contains additional options for the collection. db.collection.insert( <document or array of documents>, { // options writeConcern: <document>, ordered: <boolean> } ) You may want to add the _id to the document in advance, but...

How to add a subdocument in a mongoose schema

javascript,node.js,mongodb,mongoose

Since the address field is not required by Mongoose when you retrieve the Model from the database the field just won't be defined. Thus you won't be able to add an address field. You should check to see if it exists if(member.address === undefined){ member.address.push(new_address); } else{ member.address = [new_address];...

Meteor - Multiple data contexts with Iron Router

meteor,iron-router

Your data object declaring syntax is wrong, it should be : this.render('PackageDetails', { data: { package: package, listItems: listItems } }); Then in your template, you can reference the data context using {{package.property}} and {{#each listItems}}....

Use a “months” array to perform calculations for each month in a for loop

javascript,arrays,meteor,meteor-helper

I think you want to get the properties from your currentProject object by using the month as a key. Like this: var months = ["jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","des"]; var arrayLength = months.length; var rtcw = {}; for (var i = 0; i < arrayLength; i++) { alert(months[i]); // Need to Calculate rtcw for...

MeteorJS Blaze.getData() occasionally returns undefined

meteor,meteor-blaze

It turns out the issue was within the click event. I had a nested span element within my share-course button: <small class="share-course" data-courseid="{{_id}}"> Share <span class="glyphicon glyphicon-share"></span> </small> This was messing up the way I was targeting my embedded courseID Instead of Blaze.getData(), I should have also been using Template.currentData()...

What is cursor?

meteor

The Meteor cursor is like a lazy version of the array of documents. It's designed to iterate through the results of a query while not actually loading each of the documents until they are actually requested or the cursor is at the position containing the document. Its better to think...

Cassandra data model to store embedded documents

mongodb,database-design,cassandra

If your document nesting level is not too deep, you can use User Defined Types from C* 2.1. I personally suggest to rethink your schema into more flat form like: create table profiles ( name text, name2 text, email text, username text, ts timestamp, primary key (name,name2) // compound primary...

mongodb populate method not working

node.js,mongodb,model,populate,auto-populate

When you create an instance of the Post model, you need to assign the _id from the user as an ObjectId, not a string: var ObjectId = require('mongoose').Types.ObjectId; Post.create({ text: 'farheen123', created_by: new ObjectId('5587bb520462367a17f242d2') }, function(err, post) { if(err) console.log("Farheen has got error"+err); else console.log(post); }); ...

Insert data in collection at Meteor's startup

javascript,json,meteor,data,startup

Ok, you'll want to check out Structuring your application. You'll have to make the file with the definition load earlier, or the one with the fixture later. Normally you have your collections inside lib/ and your fixtures inside server/fixtures.js. So if you put your insert code into server/fixtures.js it'll work....

What are some patterns I can look at for database implementations in JavaScript?

javascript,node.js,mongodb

That's a pretty wide question, partly opinion based. This question should be closed, but I still want to give you some advice. There once was the Active Record pattern, which has been proven to be pretty difficult to maintain. The solution was the DAO pattern, but this adds a lot...

Meteor: onRendered doesn't get fired again after second render iron-route

javascript,meteor,iron-router

onRendered only fires when an instance of the template is added to the DOM, it will thereby not fire again on data changes. If you want to execute code once the data is ready you should use the template.autorun function like so: Template.profielBewerken.onRendered(function () { this.autorun(function (comp) { if (Meteor.user())...

Turning the Stripe Checkout into a Synch function

meteor,stripe-payments

This should work and result should populate with a result as you see in the stripe documentation: var result = stripeChargesCreateSync({ source: stripeToken, amount: (info.timeRequired/15)*500, // this is equivalent to $50 currency: 'gbp' }); This is where the error is, use this: var stripeChargesCreateSync = Meteor.wrapAsync(Stripe.charges.create, Stripe.charges); instead of var...

How to get node.js to connect to mongolab using mongoose

database,node.js,mongodb,mongoose,mongolab

Try using db = mongoose.connect(uri); instead of db = mongoose.createConnection(uri); ...

Getting failed to load c++ bson extension error using Mongodb and Node.js

javascript,node.js,mongodb

Since you're using the mongojs module, you're going to have to connect to the database using the following method db = mongo("127.0.0.1:27017/"+db, collections); ...

How to use a variable as an Object Key [MongoDB] [duplicate]

node.js,mongodb

JavaScript has no nice notation for creating an object where the keys are variables: var $push_query = {}; $push_query[name] = item; ... {"$push": $push_query} ... ...

Why the query scans 8x times the documents it finds - MongoDB

mongodb

It's not "documents" it's "Objects" as is stated, but you would not be the first person to not fully understand the .explain() output. Put simply, you have as part of your index an "array" element (actually the maximum "two" allowed), which means that your index is what we call "MultiKey"....

Meteor Iron Router not loading template

javascript,meteor,iron-router

Your call to the Router.map function is unnecessary. It doesn't do much, as you can see here. Also you can omit the onBeforeAction hook if you're just calling this.next(). But I too, don't see anything wrong with your code. Here are some things you could try tho: Check if your...

Disabling tail.sh for specific server ( or environment )?

javascript,meteor

I think this feature should be disabled for dev environments. It will probably be done so :] Not sure if this counts as an answer. I made a GH ticket to track the progress until its updated: https://github.com/Tarang/Meteor-Analytics/issues/28...

Use JSON file to insert data in database

javascript,json,mongodb,meteor,data

Simple use underscores _.extend function. Like this: var newProfile = _.extend( JSON.parse(Assets.getText('test.json')), {user: id} ) Profiles.insert(newProfile) ...

AngularJS factory dependencies

javascript,html,angularjs,mongodb

DOCS Change your factory to service as you are using this factory return an object or primitive type not bind with this app.services('articleFactory', ['$q', '$http', function ($q, $http){ this.getAllArticles = function (){ var deferred = $q.defer(), httpPromise = $http.get ('/entries'); httpPromise.success (function (data){ deferred.resolve (data); }) .error (function (err){ console.log...

Compare Array with Collection-Array containing Objects

node.js,mongodb,mongoose,schema

You can try this: objectModel.find({ 'members.user_id' : {'$in' : ['asdf123lkd', 'asdf1223']} }, function(err, data) { console.log(err,data); }) ...

Meteor/MongoDB limiting the result

mongodb,meteor

Meteor's collection API is somewhat different from that of the mongo API. find takes up to two parameters: a selector object, and an options object. options allows you to specify such things as sort, skip, limit and fields, in addition to the meteor-specific reactive and transform.

using MongoDB aggregate count subdata

mongodb,aggregate

please try the below query : db.collection.aggregate( [ { "$unwind": "$data.order_goods" }, { "$group" : { "_id" : "$data.order_goods.category", "total": {"$sum":1} } }, { "$project" : { "category" : "$_id" , total : 1 } ] ); ...

Query an array of embedded documents in mongodb

mongodb,embedded-documents

You can push the item into the array with the following command: db.mycollection.update({ _id: "zinfandel", "last_search.engine": { $nin: ["notwellknownengine.com"] } }, { $push: { "last_search": { "engine" : "notwellknownengine.com", "query" : "stackoveflow.com" } } }); ...

Creating meteor autoform w/ array of radio buttons

meteor,meteor-autoform

Yup! You can simple define arrays in SimpleSchema using this notation: ... 'problems': { type: String, autoform: { afFieldInput: { options: function () { return { one: 'one', two: 'two', three: 'three', four: 'four', five: 'five', six: 'six', } } } } } ... And in your template {{ >...

TypeError: Cannot read property 'slice' of null

meteor,meteor-autoform,meteoric

This is a issue with the new patch for autoform-ionic to the new versions of autoform. Apparently some labels are skipped, some not (see here). In order to fix that and avoid this error when your input type is not there (for example, type = number), all your schema fields...

MongoDB Java Driver 3.0 MapReduce

mongodb,mongodb-java

Yes, this is the expected behavior. Since the MapReduceIterable is a fluent interface, there must be some way to signal the driver that it's time to actually do the map-reduce, and currently the only way to do that is to start iterating. If you really don't need the results, and...

Async await usage for MongoDB repository

c#,mongodb,asynchronous,parallel-processing,async-await

When you call an async method you should await the returned task, which you can only do in an async method, etc. Awaiting the task makes sure you continue execution only after the operation completed, otherwise the operation and the code after it would run concurrently. So your code should...

Creating index while updating the documents

mongodb,indexing

The amount of time it takes to add the index would depend on your hardware, but with 20206 records a simple index as you describe shouldn't take very long for most hardware. Queries fully covered by the index (i.e. where you specify A and B, or just A, but not...

paging subdocument in mongodb subdocument

mongodb,mongodb-query

Though this is possible to do with some real wrangling you would be best off changing the document structure to "flatten" the array entries into a single array. The main reason for this is "updates" which are not atomically supported by MongoDB with respect to updating the "inner" array due...