w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Mongoose - Query nested objects
I think that this query may be the thing you're looking for... { comments: { $elemMatch: { _id: 111, likes: user_id1 } } } Hope it helps you

Categories : Node Js

Query nested object dynamically in Mongodb + Mongoose.js
var user_id = req.params.id; var query = {}; query['ratings.' + user_id] = {$exists: true}; Item.find(query, function(err, items) { ... }); The key in the object you send to Item.find have to be a string. To construct a string of any arbitrary values you have to first create the object and then use the bracket notation to define it (that is: query[anything+here] = data).

Categories : Javascript

A SQL query for nested update in mysql
SQL> update table_name set flag = 'N' where id = 2 and flag = 'Y'; --if your flag's datatype is char than you have to put it in '' either you don't need to use it. It will update only those flags which's id is 2 and flag value is 'Y'. before updating please run select statement and keep in mind how many records it returned and while updating number of updated record must be same. if both are same only then commit it. / reply and vote if it works

Categories : Mysql

Nested Repeater Puzzle: Using data returned from (outer) query, in a nested query
Couple of things that should be fixed here: The error "Server tag not well formed" was due to missed double quote after ConnectionString attribute. Remember that everything that goes inside <%# %> must be a valid C# code, which means that that if your are using a string - you should enclose it into double quotes. Typical pattern for quotes here is AttributeName='<%# Eval("Property")%>'. That was not the case in the SelectCommand value. When you need to manipulate with both literals and bound data, like in the select query here, it is better to enclose the whole expression in the servlet tags and perform necessary transformations inside. All in all, here is the result: <asp:Repeater ID="Repeater1" runat="server" DataSourceID="SqlDataSourceGrantCategories"> <Ite

Categories : C#

Mongoose: nested ref models population
var Group = mongoose.model('Group', GroupSchema); Group.find().populate('_item').populate('_meta').exec(function (error, groups) { //groups will be an array of group instances and // _item and _meta will be populated });

Categories : Node Js

Nested Arrays in Mongoose with ObjectId
I think your problem stems from your schema. You should try to define a schema in which the keys are not dynamically changing. MongoDB does not support queries on the keys of documents, just the values. I think that using a dynamic "ObjectID" as the key in your schema above is leading to weirdness with Mongoose, and causing your issue. But, even if your query were propagated properly to MongoDB, it would still not produce the output you desire. The reason for this is that MongoDB will interpret "postID" as a String, regardless of whether you've defined some postID variable to hold a dynamic value. This is the output if you run the query from the mongo shell, using a variable postID: > var postID = 1234 > db.users.update( {twitterID : 102016704}, {$push : {votedPosts : {postID

Categories : Javascript

Posting nested models in mongoose
new Order() doesn't take a callback. a) Do you intend to save the "items" embedded with the Order or b) Do you intend to save the items in a separate collection or c) both?

Categories : Node Js

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

How to sort nested Datas on a Mongoose Model?
Call toObject on your mongoose model instance to turn it into a plain object you can manipulate: var doc = MyDoc.toObject(); doc.Members.sort(function(a, b) { return b.points - a.points; });

Categories : Javascript

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

Update a record where _id = :id with Mongoose
According to this question and this other one, the Mod on _id is not allowed occurs when one tries to update an object based on its id without deleting it first. I also found this github issue which tries to explain a solution. It explicitly states: Be careful to not use an existing model instance for the update clause (this won't work and can cause weird behavior like infinite loops). Also, ensure that the update clause does not have an _id property, which causes Mongo to return a "Mod on _id not allowed" error. The solution, it seems, is to do the following: var upsertData = my_visit.toObject(); console.log(req.body.id); // OK delete upsertData._id; models.visits.update({ _id: req.body.id }, upsertData, { multi: false }, function(err) { if(err) { throw err; } //.

Categories : Node Js

How to use Document#update in Mongoose?
The Mongoose api is based on the underlying MongoDB query structure. In this case, "doc" refers to a criteria for matching certain documents that you want to update. The MongoDB docs explain this very clearly: http://docs.mongodb.org/manual/core/write-operations/#update So, let's say that you had a 'cars' collection, and you wanted to find all documents (all cars) that had 3 wheels, and increment that value so those cars had 4 wheels. In this case, "doc" is { wheels : 3 }, which returns all three-wheeled cars in the collection. Here is the basic query in the MongoDB shell: > db.cars.update( { wheels : 3 }, { $inc : { wheels : 1 } } ); In Mongoose, you can add additional parameters for options and a callback function, but that's the basic idea.

Categories : Mongodb

Insert or Update into MongoDB using mongoose.js
I don't think your notion of a single route that will either update an existing user or create a new one is a good idea. Instead, consider following the REST design: app.post('/api/users', createNewUser); app.put('/api/users/:userId', updateUser); createNewUser should just make a new user object with the proper attributes and call save on it. updateUser can do User.update({_id: req.params.userId}, fieldsToChange.... See if you can make that work to start and don't add complications like checking for already registered users until a simplistic create/update pair works OK and you feel confident. Then you can evolve your code to be more robust and realistic, but go step by step.

Categories : Node Js

What's wrong with my php/sqli update query? (Update query can't read customer_ID correctly)
I would suggest that you bind your own defined variables as parameters instead of the actual $_POST data. if($stmt->bind_param("sssiissssii",$fname,$lname$email, ... ,$customerid)) { $fname = $_POST['fname']; $lname = $_POST['lname']; $email = $_POST['email']; ... $customerid = $_POST['customer_id']; } else { //error message here then exit } It has something to do with the internals of the bind_param method. Please give it a try then let me know how it goes. Also, the way you test you do error handling in updatecustomer.php could use some changes. If the prepare statement fails, its already a given that everything after it will fail. Same goes for the succeeding method calls. They will fail if the method before them fails, might be better if you exit() after printing the er

Categories : PHP

Mongoose update document Fail with findByIdAndUpdate
findByIdAndUpdate is a static method: var landmarkModel = mongoose.model('landmark', landmarkSchema, 'landmarks'); var lm = req.body; delete lm._id; landmarkModel.findByIdAndUpdate(req.body._id, lm, console.log); Note that landmarkModel accepts plain js objects. If you already have a mongoose object then it's best to use save instead: var landmarkModel = mongoose.model('landmark', landmarkSchema, 'landmarks'); landmarkModel.findById(req.body._id, function (err, lm) { if (err) return next(err); //adding data to schema here, like: lm.name = req.body.name; lm.save(console.log); });

Categories : Node Js

Mongoose's model.update not working in Node.js
I was able to get this working with node-mongodb-native. I'm still not sure why Mongoose wasn't working, but at least I got something to work. var query = {"label": "Average Tons per Delivery"}; var update = {"type": "vertical"}; var options = {}; MongoClient.connect('mongodb://localhost/db', function(err, db) { if(err) throw err; db.collection('justgage').findAndModify( query, [['_id','asc']], {$set: update}, options, function(err, object) { res.jsonp("Ok"); }); });

Categories : Javascript

Mongo/Mongoose Invalid atomic update value error
I had the same issue. I ended up by using finOne() method create a new one if no found, update the existing one if found. I know there are two operations. but I just haven't find any way to do it in one step.

Categories : Database

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

To to do a parallel "Query" in Mongoose
It's not about Mongoose. Node.js is an asynchronous language, so it allows you to execute any number of async tasks (e.g. querying a database) at the same time. What you need is some lib to handle asynchronous control flow, like async.js or when.js: var when = require('when'); var someWork = function(callback) { when.all([ collection1.find(query1).exec(), collection2.find(query2).exec() ]).spread(callback) .otherwise(function(err) { // something went wrong }); }; when.js is a module to handle promises. So, if you don't need promises, you may use async.js instead: var async = require('async'); var someWork = function(callback) { async.parallel([ function(cb) { collection1.find(query1, cb) }, function(cb) { collection2.find(query2, cb) } ], functi

Categories : Node Js

When update nested collection in meteor, how to pass variable for the update path
It doesn't work because you can't use dynamic keys for object literals in javascript. You need to use bracket notation and build up the object you want to use in the update. For example: var city = 'NYC'; var object = {}; object["address." + city] = 'new address'; MyCollectionName.update(idOfObjectToUpdate, {$set: object}); Your last example should work, assuming Collection is actually the name of a collection, and {sel} is the correct selector for what you are trying to do.

Categories : Javascript

Can't get $or query to work in NodeJS with Mongoose
find will actually return a cursor, even when only one record matches, you will need to iterated through the cursor, try this: myModel.find({$or: [{_id: my_id}, {external_id: my_id}]}).nextObject(function (err, model) { ... }

Categories : Node Js

MySQL - Reference main query in nested select (need to be nested)
This cannot work. SELECT clause is always evaluated at the end of the execution chain, @teamg_id variable will always be 0 in the nested subquery. Try this query, it is not tested (I can't see your data, playing whith sample data always helps), but probably it gives desired results. I commented out some parts and add one join condition. /* SET @teamg_id := 0; */ SELECT /* @teamg_id := player.team_id, */ player.team_id AS player_team, event.local_team_id AS local_team, event.visitor_team_id AS visitor_team, action.unique_id AS action_id, action.player_id AS player_id, player.name AS player_name, playerindex.rank AS player_pos, playerindex.ses_var_nest AS ses_var_nest FROM er_players player

Categories : Mysql

node + express + mongoose query authentification
YEah robert klep was right on the money, After i seearched the mongoose Documentation and the mongodb docs as well, it became clear that queries return a mongo document object, in terms should be converted to the same object or variable types for opperands to work.

Categories : Javascript

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

Mongoose Static Not Returning Object After Query
What about using a callback function? userSchema.statics = { getMongoIdByTwitterName : function (twittername, callback){ this.findOne(findOne({twitterID : req.user.id}, callback(err, user); ) } }

Categories : Mongodb

Mongoose query.select() Not functioning properly?
You cannot combine inclusion and exclusion semantics in a single projection with the exception of the _id field. mongodb projection

Categories : Javascript

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

MongoDB (and Mongoose.js): Does the order of query conditions matter?
I'm a little confused by your question, simply because the index you provide ({ first_name: 1, archived: 1 }) is a compound index. All of the following queries will make use of that compound index: conditions = { archived: false, first_name: "Billy" }; conditions = { first_name: "Billy", archived: false }; conditions = { first_name: "Billy" }; Now, let's assume we have two separate indexes, { first_name: 1 } and { archived: 1 }. In this case, MongoDB will do query optimization to determine which index is the most efficient to use. You can read more about the query optimization performed by MongoDB here. The MongoDB query optimizer will thus likely use the same index for both of the multicondition queries you provided: conditions = { archived: false, first_name: "Billy" }; conditions

Categories : Mongodb

Mongoose Query Data in Express.js Node.js ,get the wrong result
(not sure if this is causing the problem, but it seems worth mentioning anyway) Here, you're passing req.cookies.session, which is an object: userModel.checkSession(req.cookies.session, ...); But in checkSession, you're assuming it's an id: UserModel.prototype.checkSession = function(sessionID, callback) { sessionMongooseModel.findOne({sessionID:sessionID}, ...); Just out of curiosity: any reason why you're not using one of the existing MongoDB-backed session stores for Express (like this one)? Also, Mongoose has it's own way of adding class methods to models, using statics.

Categories : Node Js

Express cookieSession and Mongoose: how can I make request.session.user be a Mongoose model?
Express session is stored as separate storage and has limitations to what can be stored there. It cannot store prototype data (methods). Look at it more like key<>value storage. Reasons for this is that session can be stored anywhere (pretty much), such as: process memory; databases (mongodb); redis; etc. Because of this, once you put anything in session object and request is finished, express will take session data, parse it and stick into session store just as pure object. By default it is process memory, but as mentioned before - can be any other storages. So when next http request happens, session middleware will try to restore session using cookie (if it is used) data in request headers, and will ask session storage to provide data back. As it is already formatted - it will n

Categories : Node Js

Mongoose connect method fails on simple Node Server. Express, Mongoose, Path
You need to actually successfully get mongod running and listening for connections. Just type mongod with no options, hit ENTER, and let it run. Then in a separate terminal start your express app. Note that mongod is the mongodb server daemon whereas mongo is the command line client where you can run an interactive REPL and issue database commands.

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

equivalent hql query? (query with nested query in FROM clause)
Every technology has its limits. HQL is no exception: There are some queries that can not be expresses as HQL. In situations like this, I just use createNativeQuery(), which accepts regular SQL, and move on.

Categories : SQL

CodeIgniter single update query to update one column with an existing columns data?
Try like this .. $data=array('last_login'=>current_login,'current_login'=>date('Y-m-d H:i:s')); $this->db->where('id','some_id'); $this->db->update('login_table',$data);

Categories : PHP

Is it possible to build a query that does the update first with where and join conditions and if update exists then inserts?
Impossible to give you a full answer with the limited details above, but as Loopo says you can use INSERT....ON DUPLICATE KEY UPDATE . For example, based on your UPDATE:- INSERT INTO ASSET_ASSOCIATION(ASSET_ID, ASSOCIATED_ASSET_ID, ASSET_FIELD_ID) SELECT a.ID, b.ID, 46 FROM ASSET a INNER JOIN HD_TICKET ON HD_TICKET.CUSTOM_FIELD_VALUE2 = a.NAME INNER JOIN USER U ON U.ID = HD_TICKET.SUBMITTER_ID INNER JOIN ASSET b ON U.FULL_NAME LIKE BINARY CONCAT('%',b.NAME,'%') AND b.NAME <> '' WHERE ASSET.ASSET_TYPE_ID = 5 AND HD_TICKET.ID = 120 ON DUPLICATE KEY UPDATE ASSOCIATED_ASSET_ID=VALUES(ASSOCIATED_ASSET_ID) This is assuming you have a unique key on asset_id and asset_field_id. However almost certain your table is more complex than this.

Categories : Mysql

MongoDB update query (update an array field in document)
You are using the array operator push with a data structure that is not considered by MongoDb as an array (array must have 0-based ascending numeric indexes). You must treat it as an object. So you have 2 choices. If in [21] => 0, the value 0 is useless (and I don't expect so), you can use a true array: "emailQueries" : [21,22] and you can use the push operator in the PHP code like this $collection->update( array('email' => $user['email']), array( '$push' => array( 'emailQueries' => (string) $email_id ) )); On the other hand, if you must keep the value 0, and for instance, increment it, you have to considered your EmailQuery as an object : "emailQueries" : { "21" : 0, "22" : 0 } So you c

Categories : PHP

MySQL: Can I stop an UPDATE query in the BEFORE UPDATE trigger?
Looking at the manual (http://dev.mysql.com/doc/refman/5.5/en/signal.html) the SIGNAL statement is what you are looking for. IF NEW.variance <> 0 THEN SIGNAL error SET MESSAGE_TEXT='Variance is not 0.'; END IF

Categories : Mysql

Combined Update Query with single update statement
Please try: update dbo.FACOD set LowValue=(case when Fieldname in ('AYStartDate','Dateloanstart')and AwardYear='2012-13' then '07/02/2010' when Fieldname in ('AYStartDate','Dateloanstart')and AwardYear='2013-14' then '07/02/2011' else LowValue end), HighValue=(case when Fieldname in ('AYEndDate','DateloanEnd')and AwardYear='2012-13' then '06/30/2015' when Fieldname in ('AYEndDate','DateloanEnd')and AwardYear='2013-14' then '06/30/2016' else HighValue end) where Fieldname in ('AYStartDate', 'Dateloanstart', 'AYEndDate', 'DateloanEnd')and AwardYear IN ('2012-13', '2013-14')

Categories : SQL

block rows for select query till update query is done its job
In Oracle, readers never block writers and writers never block readers. So another session will always be able to read the current committed state of a row regardless of what the update process is doing. If you want to prevent the rows from being read, you would need to code some additional locking logic. The reader could also do a SELECT ... FOR UPDATE with or without a WAIT so that it would block until the writer's transaction commits. You could also build locking logic using a different table. You could build some logic where the writer updates a row in a different table indicating that the update process is underway and all the reader processes could read that row.

Categories : Hibernate

SQL query with nested query on another table in it
Use update master_email_list l inner join email_bounces b on b.email = l.email set bounce = 1 You could also try to deactivate keys during the update to speed things up: ALTER TABLE master_email_list DISABLE KEYS; And afterwards ALTER TABLE master_email_list ENABLE KEYS;

Categories : Mysql



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