w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Dynamic Mongoose Find using AND style query
Well, you can't have an AND with 2 values for the same property (hex) as that's not possible, so I assume you want both an AND clause and an OR clause like below. AND is the default for your conditions object, so you just need to $or your hex values. clrModel.find({ 'img.perc': {$gte: 5}, $or: [ {hex: "5B6D8B"}, {hex: "BA4D2A"} ] }, 'img.path', function(error,data) {.... Another variant that should return the same results: clrModel.find({ 'img.perc': {$gte: 5}, hex: {$in: ["5B6D8B", "BA4D2A"]} }, 'img.path', function(error,data) {....

Categories : Node Js

How to find docs with arrays in which elements match some other element in another array?
Instead of doing a regular expression match, you could split out the first letter its own subkey as well: { name:"Product A", parts: [ { s: "W", ku: "W-01" }, { s: "Y", ku: "Y-01", qty:2 } ] } Otherwise you can simply do this regular expression match — you don't need the $elemMatch here either. db.products.find( { "parts.sku: /^[YZ]/ } ); But it is better to use an $or for each of them, as then at least a little bit of the index can be used as the regular expression search is now a fixed-prefixed regular expression that internally gets rewritten to a range query (Y <= x < Z) or (Z <= x < [): db.so.ensureIndex( { 'parts.sku': 1 } ); db.products.find( { $or: [ { "parts.sku": /^Y/ }, { "parts.sku": /^Z/ } ] } );

Categories : Java

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

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

Mongodb return documents AND the array elements that match query
Yes, the aggregation framework will help you do this. Something like this query should work: db.collection.aggregate( { $unwind : "$list" }, // deconstruct the array { $match : { list : { $gt : 100 } } }, // match based on your condition { $group : { _id : "$_id", list : { $push : "$list" } } } // rebuild array ) You'll have to change this query based on your exact data structure, but that's the general idea.

Categories : Mongodb

PhantomJS and Karma, Selector [ng:model="query.name"] did not match any elements
The root cause of the failure was that the PhantomJS is built with an old version of JavaScript that is missing the "bind" implementation (Why PhantomJS doesn't have Function.prototype.bind) The controller logic was using currying, with the bind method, and thus caused the page render incorrectly. I found this out when exporting a rendered page with the phantomJS browser. I removed all the bind method calls from the controller code and End2end test(s) are now passing as as expected. I apologize that from the information that I have provided for the issue, it is impossible to deduct the problem cause.

Categories : Angularjs

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

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

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

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

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

Mongoose – how to limit depth of populate() level?
From the mongoose docs: It is debatable that we really want two sets of pointers as they may get out of sync. Instead we could skip populating and directly find() the stories we are interested in. I would remove the reference of blogs in the category schema and just query for the documents that you are interested. "Blog object contains an array of Category objects (refs) to be able to get all the categories this blog is related to": Blog.findOne({_id: blogId}) .populate('category') .exec(function (err, blog) { callback(err, blog); //blog.category is the array you want }) "Category object contains an array of Blog objects (refs) to be able to get all the blogs of this category": Blog.find({category: catId}) .exec(function (err, blogs) {

Categories : Node Js

Populate method not returning documents - Mongoose
You're using Status in AccountSchema before it's defined. However, you should actually be using StatusSchema (the schema) instead of Status (the model) in the definition of AccountSchema anyway. Try this instead: var AccountSchema=new mongoose.Schema({ email:{type:String,unique:true}, password:{type:String}, name:{ first:{type:String}, last:{type:String}, full:{type:String} }, contacts:[Contact], status:[StatusSchema] });

Categories : Node Js

Use mongoose populate methods but still return ObjectID rather than documents
You need to pass the path to populate to the populate call instead of the model name: PlanModel.findOne({'_id':pid }, { 'plan':{ $slice: [ number, 1 ] }, 'plan.tasks':1,'plan.goal':1 }) .populate('plan.tasks', 'task_description') .exec( function(err, doc) { if(err){ callback(err, null); } else { callback(null, doc); } } )

Categories : Node Js

How Express/Mongoose populate data to HTML select tag
I don't quite understand your question completely since the question has many parts but it seems like you're trying to avoid asynchronous paradigm. You can wait for mongoose objects to be populated before rendering them with template. You can either force async behavior in node https://github.com/caolan/async#parallel async.parallel([ function(callback){ CreatorModel.find({}).exec(function(err, crts) { creators = crts; callback(creators); }); } ], // optional callback function(err, creators){ res.render('tasks/create-form', { creators: creators, assignees: assignees }); } Or use QueryStream to pipe it to res.render http://mongoosejs.com/docs/api.html#querystream_QueryStream Later on, you c

Categories : Node Js

Mongoose Relationship Populate Doesn't Return results
The ref field should use the singular model name Also, just do: models.Security.findById(req.params.id).populate('_bids').exec(... My main suspicion given your snippet at the moment is your req.body.order has _security as a string instead of an array containing a string. Also, you don't need an id property. Mongodb itself will automatically do the _id as a real BSON ObjectId, and mongoose will add id as a string representation of the same value, so don't worry about that.

Categories : Node Js

SQL Query to Find Matching Records but Excluding those that Match Second Criteria
Give a try with below query: (SELECT d.DocID, s.SignID FROM Documents AS d) temp1 INNER JOIN Signatures AS s ON d.SignID = s.SignID WHERE s.SignatoryName = 'Search Name Here' and d.DOCID not in ( select DocID from temp1)

Categories : SQL

I am getting 'TypeError: Cannot call method 'path' of undefined' while doing nested populate in Mongoose
var opts = [ { path: 'subcategories.products' } ]; Category.populate(docs, opts, function(err, docs2) { subcategories.products is an unknown path for the Category schema so you'll need to change the model used for population. Either of the following two approaches will work: // 1 var opts = [ { path: 'subcategories.products' } ]; Product.populate(docs, opts, function(err, docs2) { or // 2 var opts = [ { path: 'subcategories.products', model: 'Product' } ]; Category.populate(docs, opts, function(err, docs2) {

Categories : Node Js

What best way to populate java list with separate elements and elements from other lists?
You could at least introduce a loop: List<WebElement> containers = Arrays.asList(inetConnection, wiredConnection, phonesConnection, usbConnection, wifiConnection); List<WebElement> list = new LinkedList<WebElement>(containers); for (WebElement e : containers) list.addAll(e.getExpectedElements());

Categories : Java

Which is faster and better to use - query db or iterate over array to find sum of elements
Do the second method. Database aggregate queries execute much faster than PHP code for the same purpose. You have to think of the following heads I am assuming you only need the sum, and not the rest of the rows Execution Time Your database software is better at aggregate queries than PHP. PHP will have to iterate over each instance once it has received the data to calculate the sum. Its better to do this in the database, if possible, since it is dealing with the data anyways and has optimized functions to do this sort of thing. Data Transfer If all you need is the sum, you are sending a number of rows, their column values that you don't really need. For the sum, you transferring just a single number. If the rowset is large, there will be significant overhead in transferring and might

Categories : Symfony2

Mongoose: aggregation with $match by "_id.property"
As I workaround I included a $project before the match, but I am still looking for a cleaner solution: { $project: { "_id": 0, "owner": "$_id.owner", "value": 1 } }

Categories : Node Js

XPath getting text from all elements that match XPath query
This works for xpath 2.0: string-join(/*/text(), ' ') Tested here, prints: Hello World !!! This is cool

Categories : PHP

Is it possible to use the Mongoose query builder to just return an aggregation pipeline array and not run the query?
Looking through the source, it looks like whenever you're using the aggregate() function, the pipeline is stored in a property called _pipeline. Using your example, if you write an aggregation pipeline like this... var myAggregation = Model // "Model" should actually be the name of your model .aggregate() .match({ value: { $gt: 1000 } }) .match({ category: { $in: [1, 2, 3] } }) .sort('-date') .skip(100) .limit(10); Then myAggregation._pipeline will look like this... [ { '$match': { value: { $gt: 1000 } } }, { '$match': { category: { $in: [1, 2, 3] } } }, { '$sort': { date: -1 } }, { '$skip': 100 }, { '$limit': 10 } ] I noticed, however, that you're using the where() function, which actually creates a Query in mongoose instead of an aggregation pipeli

Categories : Mongodb

MySQL query to find child record where 2nd child table entries do not match
Based on your update this should be a start. Select s.Description From Structure s inner join structure_version sv On sv.structure_id = s.id inner join Structure_version_range svr on svr.structure_version_id = sv.id inner join structure_version_range_partner svrp On svrp.structure_version_range_id = svr.structure_version_id inner join item_version iv on iv.structure_id = s.id Left join item_version_partner ivp On ivp.item_version_id = iv.ID and ivp.partner_id = svrp.partner_id Where ivp.partner_id is null Have a play with it the concept is pretty simple, it's just the normalisation that you've implemented makes it a bit windy. Selecting the partner_ids from the two tables and dropping the where clause will demonstrate how it works.

Categories : Mysql

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

MySQL php array - find values from array that do not match query
This query returns rows that doesn't have the job id you specified but has the user_id, $query="SELECT job_id FROM table WHERE job_id NOT IN('$job_id') AND user_id='$user_id'"; if you want the job ids that doesn't have the user id then use. $query="SELECT job_id FROM table WHERE job_id IN('$job_id') AND user_id!='$user_id'";

Categories : PHP

Populate table where columns match | TSQL
SQL Server solution: You could try one of these solutions: IF EXISTS(SELECT * FROM tempdb.sys.columns c WHERE c.object_id=OBJECT_ID(N'tempdb..#MyTempTable' AND c.name='Age') BEGIN INSERT INTO #MyTempTable(Name,Age) SELECT ... FROM ... CROSS APPLY XmlCol.nodes('/...') a(b) END ELSE IF EXISTS(SELECT * FROM tempdb.sys.columns c WHERE c.object_id=OBJECT_ID(N'tempdb..#MyTempTable' AND c.name='Race') BEGIN INSERT INTO #MyTempTable(Name,Race) SELECT ... FROM ... CROSS APPLY XmlCol.nodes('/...') a(b) END or INSERT INTO #MyTempTable(Name,Age,Race) SELECT ... AS Name, a.b.value('(@Age)[1]','TINYINT') AS Age a.b.value('(@Race)[1]','NVARCHAR(50)') AS Race, ... CASE WHEN <condition for Race column> THEN value ELSE NULL AS Race FROM ... CROSS APPL

Categories : Sql Server

How to find nscanned in mongoose?
Not directly. However, what you can do is enable Mongoose's debug logging so that you can copy the query its executing and then paste it into a MongoDB shell and run explain() on it. To enable Mongoose's debug logging to the console, add the following to your code: mongoose.set('debug', true);

Categories : Node Js

How to find all the collections from mongoose
You can use the collectionNames function to return a list of collections. db.on('open', function(){ mongoose.connection.db.collectionNames(function(error, names) { if (error) { throw new Error(error); } else { names.map(function(cname) { console.log(cname.name); }); } }); }); => database1.system.indexes => database1.users => database1.posts

Categories : Mongodb

how to do a full outer join that will populate with their joing criteria regardless if they don't match up
COALESCE the two accsnnums. This function takes the first nonmissing value, so if labtable.accsnnum is available it takes that; otherwise it takes rslttable.accsnnum. proc sql; create table both as select coalesce(labtable.accsnnum,rslttable.accsnnum) as accsnnum label="Access Number", Labtable.Lab_lbcount label="Lab_lbtestcd_count", Rslttable.Rslt_lbcount label="Rslt_lbtestcd_count", Lab_lbcount-Rslt_lbcount as difference from work.Labtable full outer join work.Rslttable on Labtable.accsnnum = Rslttable.accsnnum; quit;

Categories : SQL

Regex - Find the match that is inside a match
You can try this regex: /href=[^>]+.pdf/ regex101 demo Most of the time, when you can avoid .* or .+ (or their lazy versions), it's better :) Also, don't forget to escape periods.

Categories : PHP

Mongoose find with reference to object
What you need is a closure since the loop, and item with it, will be done before any callback is called. for(var idx in items){ (function(item){ Model.find({'_id': item.id}, function(err, matches){ console.log(item); }); })(items[idx]); } Which should be pretty much the same as the following (assuming items is an array): items.forEach(function(item){ Model.find({'_id': item.id}, function(err, matches){ console.log(item); }); })(items[idx]);

Categories : Node Js

Excel VBA populate listbox with data from sheet using only rows that match variable
x = Cells(var_nextline, 2) should give an error, as the right-hand side returns the cell object, not the value contained in the cell, and assignment of objects must be done by using Set. Anyway, it is not what you want to have. Try x = Cells(var_nextline, 2).Value2 Remark: You could improve your code: Public Sub UserForm_Initialize() Dim var_associate As String var_associate = "Kirsty" Dim var_nextline As Integer var_nextline = 1 Dim x As String Do x = Cells(var_nextline, 2).Value2 If x = "" Then Exit Loop If x = var_associate Then Me.lsb_upsell.AddItem(x).Value End If var_nextline = var_nextline + 1 Loop End Sub Second remark: Where is Cells initialized (e.g. with Set Cells = ActiveSheet.Cells)? Add Option Explicit a

Categories : Excel

PHP MySQL query: match two tables with percentage match
Try below: SELECT e_id, e.skill, c.skill, (e.points/c.points)*100 from employee_skills as e, company_skills as c WHERE e.skill = c.skill GROUP BY e.e_id,e.skill See below: SELECT c.skill, total_emp_points, c.points as total, (total_emp_points/c.points)*100 as percnt FROM company_skills AS c, (SELECT e.skill, SUM(e.points) as total_emp_points FROM employee_skills as e GROUP BY e.skill) as emp WHERE c.skill = emp.skill; see SqlFiddle

Categories : PHP

Mongoose: Find all tags for a specific set of articles
As pointed out by WiredPrairie, distinct was the solution. var query = { /** Query for the articles that I want tags from */ }; //Using mongoose-q return Article.distinctQ('tags', query);

Categories : Mongodb

find id of latest subdocument inserted in mongoose
Mongoose will automatically create an _id for each new sub document, but - as far as I know - doesn't return this when you save it. So you need to get it manually. The save method will return the saved document, including the subdocs. As you're using push you know it will be the last item in the array, so you can access it from there. Something like this should do the trick. m['b'].push({ba:235,bb:"World"}); m.save(function(err,model){ // model.b is the array of sub documents console.log(model.b[model.b.length-1].id); });

Categories : Node Js

how to find any document in database with an object id with mongoose?
Operations in MongoDB only always work on one collection. If you want to do a find on multiple collections, then you need to run multiple queries - one per collection. Of course, it's quite for Mongoose to implement a convenience function for that, but I don't think it has, or should, as it is against one of MongoDB's paradigms.

Categories : Node Js

Model.find() returns empty in mongoose
From official doc Population is the process of automatically replacing the specified paths in the document with document(s) from other collection(s). Try it without populate Model.find({}).exec(function(err, models) { if (err) { res.render('error', { status: 500 }); } else { res.json(models); } });

Categories : Node Js

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

How to formulate the following Mongoose query?
You think too relational! Right now you, I don't think you can do this efficiently as you will have to: find all B's that have c: {id} find all A's that have a b that is the set of the result from query 1 and are Active find out which B's belong to the IDs you've found in the previous query find out which D's belong to the B's you've found I think you should most definitely denormalise your schema here. For example, you can put all of the above in one document: { Active: true, containers: [ // B's { c: [ { _id: X, field1: foo }, { _id: X, field1: foo }, ] }, { d: [ { _id: X, field1: foo }, { _id: X, field1: foo }, ] } ] } And then you can just do it with one query: db.collection.find( {

Categories : Mongodb



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