w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML Categories
Mongoose.js unable to get an array from my document
console will always print the array with objects as [object object]. pages is actually an array of object, So you can specify an index to the pages array like this console.log(user[0].pages[0]); or if the pages array contain more than one element you want a regular for loop for (var i = 0; i<user[0].pages.length; i++) { // use i as an array index console.log(user[0].pages[i]); }

Categories : Json

Querying an array inside a mongoose document
You can use dot-separated paths in a query like so: User.find({'devices.deviceRegistrationId': deviceRegistrationId}). If that query doesn't match any documents, no user has that device. Note that mongo is smart enough to test all members of the devices array when given a query such as this. You can also add a user ID to your query conditions if you want to check a specific user.

Categories : Node Js

Populate with inherited document in Mongoose
Doh.. changing var componentSchema = new Schema({ name: String , desc: String }, { discriminatorKey : '_type' }) to var componentSchema = new Schema({ name: String , desc: String }, { collection : 'components', discriminatorKey : '_type' }) Fixes the issue. Not sure why.

Categories : Node Js

Using Mongoose JS to get array of pointer values for document, and expand return
Mongoose provide you a feature population which exactly does the same thing you are looking for http://mongoosejs.com/docs/populate.html. In your case what you need to do is var mongoose = require('mongoose') , Schema = mongoose.Schema var tempSchema = Schema({ title : String, artifacts : [{ type: Schema.Types.ObjectId, ref: 'Artifacts' }] }); var artifactsSchema = Schema({ title : String, media : { player: String, source: String, } }); var tempModel = mongoose.model('Temp', tempSchema); var artifactsModel = mongoose.model('Artifacts', artifactsSchema); Now whenever artifacts documents gets created you need to push that in respective temp dcoument artifacts array as shown in mongoose documentation. You can retrive it like that tempModel .find(query) .pop

Categories : Node Js

VB6 - Populate User Defined Type Array from Stored Procedure then Find Item in Array
If you are using ADO you can cache results by querying into a static cursor client-side Recordset and then disconnecting it. You can use Sort, Find, Filter, etc. and move through the rows as needed. You can even improve searches by building a local index within the Recordset after opening and disconnecting it by using the Field object's Optimize dynamic property. See: Optimize Property-Dynamic (ADO)

Categories : Arrays

How to create an array of array and populate data into it in JavaScript?
Change your code to var input = {}; $('.input').each(function(index, element) { var element_id = this.id; var element_value = $.trim(this.value); (input[element_id]||(input[element_id]={}))[index] = element_value; }); You'll get something like {"1" : {"0": "Apple", "1": "Orange"}, "2" : {"0", "Cat", "1", "Dog"}, "4" : {"0", "Coffee"} }; which isn't arrays inside arrays but maps inside maps, which seems to be more indicated for you. Now, suppose you really want arrays, then instead of strings as keys you need to have integers. Then you may do var input = []; $('.input').each(function(index, element) { var element_id = parseInt(this.id,10); var element_value = parseInt($.trim(this.value),10); (input[ele

Categories : Javascript

MongoDB - select document where all values in field array are present in a given array
Basically there are some ways to match array. There is no exact solution for your need. Considering you have documents like : { "_id" : ObjectId("51b05a712961f4704684d901"), "x" : [ 6, 7, 8, 9 ] } { "_id" : ObjectId("51b05a712961f4704684d902"), "x" : [ 7, 8, 9, 10 ] } { "_id" : ObjectId("51b05a712961f4704684d903"), "x" : [ 8, 9, 10, 11 ] } You can use query1 like: db.collection.find({x:[3,4,5,6]}) The result is exact match only for arrays like x result1: { "_id" : ObjectId("51b05a712961f4704684d8fe"), "x" : [ 3, 4, 5, 6 ] } query1 will not match : { "_id" : ObjectId("51b05a712961f4704684d8fe"), "x" : [ 3, 4, 5] } { "_id" : ObjectId("51b05a712961f4704684d8fe"), "x" : [ 3, 4, 5, 6, 7] } You can use : query2 like: db.t.find({x:{$all:[3,4]}}) result2 can be: { "_id" : ObjectI

Categories : Database

php array into javascript array document.write javascript_array
You're trying to print a Object as a string. What you need to do is to access your properties directly from the object. <script> <?php $data = array('foo' => 'bar'); ?> var my_js_var = <?php echo json_encode($data); ?>; </script> With this script, you can access your values like this: document.write(my_js_var.foo); // writes 'bar'

Categories : PHP

update nth document in a nested array document in mongodb
Q1: If you update with permalink 'jaiho' instead of 'haha', it most certainly updates the email; > db.posts.update({"permalink" : "jaiho"},{$set:{"comments.0.email":1}}) > db.posts.find() ..., "email" : 1 },... Q2: Same goes for this include; > db.posts.update({"permalink" : "jaiho"},{$inc:{"comments.0.num_likes":1}}) > db.posts.find() ..., "num_likes" : 1 },...

Categories : Arrays

Seeing array elements in mongoose js
messages is actually an array of object, So you can specify an index to the messages array like this console.log(thread_instance.messages[0]); if the messages array contain more than one element you want a regular for loop for (var i = 0; i<thread_instance.messages.length; i++) { // use i as an array index console.log(thread_instance.messages[i]); } So combine all together the code would look like this Thread.find(function (err, thread_instance) { for (var i = 0; i<thread_instance.messages.length; i++) { // use i as an array index console.log(thread_instance.messages[i]); } })

Categories : Javascript

How do I get the id of each doc when saving an array of documents with mongoose?
You can get arguments passed into any function by using the arguments object. For example: function argNum(){ console.log(arguments.length); } argNum('test',1,23,43); // Logs 4 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions_and_function_scope/arguments

Categories : Node Js

mongoose findOneAndUpdate callback with array of ids
Of course this will happen - just like any other networking on Node, it's asynchronous! This means that the callback you specified for your findOneAndUpdate operation have not run yet when it reaches the console.log(updatedArray); code. Take a look at Q for working around this common problem.

Categories : Node Js

Transform an array of documents using mongoose
You can use a lean query so that an array of plain JS objects are returned from the query and then use map to transform the array: User.find({}).lean().exec(err, users) { users = users.map(function(user) { // transform user into newuser as needed. ... return newuser; }); });

Categories : Node Js

Mongoose, index locations array
If you store values for location as 2 numbers in array, then your index would look like: coordinates: { type: [Number], index: '2dsphere', required: true } Although you need to create such index in your database: db.users.ensureIndex({ 'locations.geometry.coordinates': '2dsphere' });

Categories : Node Js

Mongoose: Array of dbref with additional property
For performance reasons I want to store a reference of all albums on the user model (is this a dbref? Yes, a DbRef is just a property in a document that is the ObjectId of a different document. Is this possible using mongoose? Yes, you can define this schema like this: UserSchema = new mongoose.Schema name: type: String required: true albums: [{ id: { type: mongoose.Schema.Types.ObjectId ref: 'Album' }, name: String ] Is the album name in the user model autoupdated if it's changed (which should happen very rarely)? Nope, but you can use a mongoose postSave hook on the Album schema to keep this denormalized data in sync.

Categories : Node Js

mongoose - Executing a query for each array element
The async library is perfect for these situations. When you have one array and want it to result in another array where there's some relation between the respective elements, .map is normally used. var async = require('async'); async.map(array, function (key, next) { // Do a query for each key model.findOne({ key: key }, function (err, result) { // Map the value to the key next(err, result.value); }); }, function (err, result) { console.log(result); // [value1, value 2, ...] }); If you have a lot of keys, async.map might overload the server sine it calls each request in parallel. If so you could use async.eachSeries. Update Of course it would also be possible to do one query for all of the values: model.find({ key: { $in: array } }, function (err, result) { result

Categories : Javascript

Setting value of an array element in Mongoose using index
Use object instead: var myIndex = { 'body.0' : 'Comment Body'}; var myIndex1 = { 'body.1' : 'xxx'}; db.Comment.findOneAndUpdate( {_id: '51fc9c329e87bf0000000001'}, {$set: myIndex}).exec(...); db.Comment.findOneAndUpdate( {_id: '51fc9c329e87bf0000000001'}, {$set: myIndex1}).exec(...);

Categories : Mongodb

Updating array within mongodb record with mongoose
It would help if you explained your intent here as naming a property "array" conveys nothing about its purpose. I guess from your code you hope to go and set the score of each item there to zero. Note your save is currently being ignored because you can only save top-level mongoose documents, not nested documents. Certain find-and-modify operations on arrays can be done with a single database command using the Array Update Operators like $push, $addToSet, etc. However I don't see any operators that can directly make your desired change in a single operation. Thus I think you need to find your record, alter the array date, and save it. (Note findOne is a convenience function you can use if you only care about the first match, which seems to be the case for you). Record.findOne({ 'owner':

Categories : Node Js

Populating an array when creating a record in MongoDB with mongoose
I've also encountered issues with populating array, the schema you defined will create a sub-doc for each array element (try dumping the array). Try changing the schema to: emails: [ type: mongoose.Schema.Types.ObjectId ] and use Member.findOne().populate({ path: 'emails', model: 'Email' }).exec(function (err, member) { res.json(200, member); }); to populate the array.

Categories : Javascript

Does Mongoose support the concept of a fixed queue array
db.myCollection.update({"arrayField.10": {$exists: true}}, {$pop: {"arrayField": 1}}) The "a.10" key checks if element 10 exists in "arrayField", which would mean the array size is equal to or greater than 10. If it does, pop 1 element off the back of the array atomically. May not be the best solution for your case, but hopefully this may set you off in the right direction.

Categories : Node Js

mongoose sub populate not works
I was just hunting down the same problem, and I believe what you are looking for is this Mongoose: deep population (populate a populated field). Basically, you are not able to do what you are trying to do, unless you do it in your callback function and then insert it in your return. I was trying to avoid that, but at the moment it seems like the only option. The other option, if you plan on doing a lot of this type of stuff, is to look into using a Relational DB.

Categories : Node Js

How should I properly use populate with mongoose?
You need to get the order right of defining query options then executing, and chainable APIs such as mongoose Query can't know what additional methods you might call AFTER the query fires. So when you pass the callback to .find, mongoose sends the query right away. Pass a callback to find query defined by arguments to find since callback is there, query immediately executes and issues command to DB then .populate happens, but it has no effect as the query has already been sent to mongo Here's what you need to do: Project.find(query, {}, { sort: { _id: -1 } }).populate("milestones").exec(function (error, results) { callback(results); }); Or a little more readable: Project .find(query) .sort('-_id') .populate('milestones') .exec(function(error, re

Categories : Node Js

Inserting Object ID's into array in existing Mongoose schema with Node.js
Keep the category names you want to search for in an array { categories: ["cat1", "cat2"] } then you can add an index to it and do a $in query. the current schema is not very good because you cannot look for the category in a single query but need to resolve all the "categories" links first.

Categories : Javascript

Having trouble iterating through array and saving to mongoose. Callback issue?
The problem with this is that the story referenced in the exec callback will have been set to whatever is the last thing iterated on in the for loop, once the callback will get executed, since all of the executed functions are referencing the same instance of the variable. The easiest way to fix this is to simply wrap each thing in the for loop in a function that you execute right away with parameters, as in: rssparser.parseURL(url, options, function(err,out){ // out.items is an array of the items pulled var items = out.items; for (var i=0; i<items.length; i++){ (function(item) { //create a mongoose story var story = new schemas.Stories({ title: item.title, url: item.url, summary: item.summary

Categories : Javascript

Populate an array with two sums
I would do it as two sequential loops: var startingIncome = 30000; var startingIncomeArr = []; var i; startingIncomeArr[0] = startingIncome; for (i = 1; i <= 45; i++) { startingIncome += (startingIncome / 100 * 3); startingIncomeArr[i] = startingIncome; } for (i = 46; i < 100; i++) { startingIncome += (((startingIncome / 100) * 3) / 2); startingIncomeArr[i] = startingIncome; } That way it's clear from the for statements themselves that the logic covers two different ranges. You also avoid an if evaluation each time through the loop.

Categories : Javascript

populate an array from dataset
here is documentation on the dataset class: http://msdn.microsoft.com/en-us/library/system.data.dataset.aspx you can access a dataset which is strongly typed with: dataSetName.dataTableName(rowIndex).ColumnName if your dataset isn't strongly typed then you can use: dataSetName.tables("tableName").Rows(rowIndex).Item(columnIndex)

Categories : Arrays

Mongoose populate multiple with references
no. mongo is no-rel db and what mongoose does is query the model you specify in the ref with the id supplied in the field data. so, refs are basically bad practice in mongo (by default of-course).

Categories : Javascript

Populate users having a given role in mongoose
When a mongodb query has someArray: someValue by default it intereprets that as "match any parent document where someArray contains someValue". So this is trivial: UserModel.find({Roles: roleId}, callback); Side note: when you ask a question about mongoose and use the word 'populate', that means mongoose's populate feature. In this case it looks like you are asking about a vanilla collection query.

Categories : Node Js

Querying after populate with RegExp in Mongoose
Something like this: model.find( { '_id.surname': new RegExp('^A') } ) .populate({ path: '_id', model: 'Author' }) .exec(function(err, authors){ ... }); The main part here is that /^A/ is a MongoDB shell specific syntax, where in JavaScript you will have to use new RegExp('^A').

Categories : Javascript

Mongoose how to populate referenced documents
For one category document, that could look something like this: // retrieve all feeds in the list and populate them mongoose.model('Feed') .find({ _id : { $in : category._feeds } }) // see text .populate('_articles') .exec(...); (I initially thought that the array passed to $in should be a list of ObjectId's, but apparently it's okay to pass an array of documents) EDIT: I think this works, too: mongoose.model('Feed') .populate(category._feeds, { path : '_articles' }) .exec(...);

Categories : Javascript

Mongoose/MongoDB removing items in model's array without stating which item
You are using splice incorrectly. var users = ['tom', 'dick', 'harry']; var index = users.indexOf('john'); users.splice(index, 1); console.log(users); //[ 'tom', 'dick' ] It's not arbitrary, you are not checking whether index >= 0. You could avoid this entirely by just changing your criteria: Document.findOne({doc_id: doc_id, users: username}, function(err, doc_data) { That query will return a null doc_data if doc.users doesn't contain that username. Or you could just check index before calling splice.

Categories : Node Js

javascript push to array inside loop during mongoose query and save
Try this: var jsonText = JSON.stringify(req.body); var jsonObject = JSON.parse(jsonText); jsonObject.forEach(function(updatebankmember, i) { var bid = ObjectID(updatebankmember._id); BankMember.findOne({ "_id" : bid }, function(error,bankmember) { if (error) { console.log(error); } else { bankmember.name = updatebankmember.name; bankmember.save(function (error) { if(error) { console.log(error); } else { jsonObject[i].id = bankmember.id; jsonObject[i].name = bankmember.name; } }); } }); }); res.send(200, jsonObject); Instead of trying to push objects into

Categories : Javascript

Unable to populate array using plist
Try this - (void)viewDidLoad { [super viewDidLoad]; self.menuArray=[[NSMutableArray alloc]init]; NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"Menu" ofType:@"plist"]; self.menuArray = [NSMutableArray arrayWithContentsOfFile:plistPath]; } you have to alloc NSMutableArray.

Categories : IOS

how to populate an array with return value objects
To access one of the CCPhysicsSprite objects at a particular index of ballArray, do this: int index; // Set this to which index of the array you wish to view. CCPhysicsSprite *sprite = [ballArray objectAtIndex: index]); If you want to access all the CCPhysicsSprite objects of ballArray, do this: int count = [myColors count]; for (i = 0; i < count; i++) { CCPhysicsSprite *sprite = [myColors objectAtIndex: count]; } Hope this answers your question.

Categories : Objective C

How to populate an empty array selectively?
I think you are trying to sum columns in an imported array. Assuming this is working: y_array1 = np.genfromtxt(filename, skip_header = 1, usecols = (0, 1, 2, 3, 4)) then y_array0 = y_array1.sum(axis=0) should give the sum of the columns. With regard to plotting, I would recommend matplotlib

Categories : Arrays

Populate PHP multidimensional array from $_POST
You can just access the array by its associative key, like this: foreach ($bund as $elem ) { // code here // The empty square brackets tells php to push the $elem value into the next available array key $va_body['bundles'][] = $elem; }

Categories : PHP

How to Populate koGrid Groups Array
I ended up having to patch the koGrid script to get the initial grouping of columns to work. If anyone else has the problem I'm happy to provide the patched script. I will look at making a pull request to get the fix into the koGrid repository after putting it through its paces a bit more.

Categories : Misc

Populate li elements with values from array
Try this : DEMO HERE HTML: <ul id='menu'><li></li><li></li> </ul> jQuery: var array = ["one", "two"]; $('ul#menu li').append(function(index){ $(this).text('Number '+array[index]); });

Categories : PHP

Possible to populate an array of structs after declaration?
Well if it is a struct, you can always do a memcpy struct two_d_obj rect = { ... }; struct two_d_obj obj_array[25]; memcpy(obj_array,&rect,sizeof(two_d_obj )); if you want to initialize more array members just loop for (i = 0; i < 25; ++i) memcpy(obj_array + i,&rect,sizeof(rect));

Categories : C

How to populate a Spinner from String array
Use ArrayAdapter this way your string array String[] test=new String[]{"test1","test2"}; your ArrayAdapter ArrayAdapter<String> gameKindArray= new ArrayAdapter<String>(MyActivityClass.this,android.R.layout.simple_spinner_item, test); gameKindArray.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); gameKind.setAdapter(gameKindArray);

Categories : Android



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.