w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
MongoDB schema design to support editing subdocuments within an array in multi-user environment?
Having different writers is a key downside of embedding documents in my opinion. You might want to take a look at this discussion that presents different solutions. I'd try to avoid different writers to one document and use a separate Comments collection instead, where each comment is owned by its author. You can fetch all comments on a post by an indexed field postId reasonably fast. Then the comments simply have a regular _id field. It makes sense to use an ObjectId because that automatically stores the time the comment was created, and it's a monotonic index by default. create a "lastModified" timestamp on the parent document, and only save the edit if nothing has changed on the document. This is called 'optimistic locking' and it's generally not good if there is a high probabilit

Categories : Mongodb

Referencing another schema in Mongoose
It sounds like the populate method is what your looking for. First make small change to your post schema: var postSchema = new Schema({ name: String, postedBy: {type: mongoose.Schema.Types.ObjectId, ref: 'User'}, dateCreated: Date, comments: [{body:"string", by: mongoose.Schema.Types.ObjectId}], }); Then make your model: var Post = mongoose.model('Post', postSchema); Then, when you make your query, you can populate references like this: Post.findOne({_id: 123}) .populate('postedBy') .exec(function(err, post) { // do stuff with post });

Categories : Javascript

Mongoose Schema with ObjectId
Are Posts a collection type in your system? If so : var userSchema = new Schema({ twittername: String, twitterID: Number, votedPosts: [{type: Schemas.Types.ObjectId , ref : 'Posts'}] }); Where 'Posts' is the name of your defined Posts model. See http://mongoosejs.com/docs/populate.html

Categories : Mongodb

getting schema attributes from Mongoose Model
Yes, it is possible. Each schema has a paths property, that looks somewhat like this (this is an example of my code): paths: { number: [Object], 'name.first': [Object], 'name.last': [Object], ssn: [Object], birthday: [Object], 'job.company': [Object], 'job.position': [Object], 'address.city': [Object], 'address.state': [Object], 'address.country': [Object], 'address.street': [Object], 'address.number': [Object], 'address.zip': [Object], email: [Object], phones: [Object], tags: [Object], createdBy: [Object], createdAt: [Object], updatedBy: [Object], updatedAt: [Object], meta: [Object], _id: [Object], __v: [Object] } You can access this through an model too. It's under Model.schema.paths.

Categories : Mongodb

Using 'generic' virtual for mongoose schema
For backbone, "id" is it's default idAttribute name, so just don't add any code there and everything will work as intended. For mongoose, the answer boils down to "it's complicated", but the main points are: By default mongoose will give each schema a virtual called "id" which will be the document's _id as a string However, by default .toJSON doesn't include virtuals, so when you send a mongoose document to backbone in the browser, it gets just "_id" and not "id" to quickly get a JSON representation including the virtuals, use myModelInstance.toJSON({virtuals: true}). You'll get both "_id" and "id" You need to read up on the transform options for toObject and toJSON to get a full picture of what you can do and how, but the gist is (based on examples straight from the docs) // specif

Categories : Node Js

Create a schema in mongoose nodejs for one record only
Yes, this is possible without anything special really other than only put 1 document into that collection. I would just leave your default set of configuration settings as a simple javascript object in code and if you find a configuration record in mongo, just use that to override the defaults via _.defaults or similar. For what it's worth, more commonly identifying the blog admin would be stored on the user record, not in a blog configuration object (user.isAdmin = true for a simple case), but either way will work.

Categories : Database

How to properly handle mongoose schema migrations?
I am doing migration like this; Let say I have db called Item. On any schema changes, I create anotherdb called ItemTemp and copy all data to ItemTemp. I executed schema change scenario on ItemTemp db. If everything goes well, I schedule db down time. I copy Item to ItemTemp again execute schema change migration and copy all data to Item db. Hope it helps

Categories : Mongodb

Adding 'virtual' variables to a mongoose schema?
This is perfectly possible in mongoose. Check this example, taken from their documentation: var personSchema = new Schema({ name: { first: String, last: String } }); personSchema.virtual('name.full').get(function () { return this.name.first + ' ' + this.name.last; }); console.log('%s is insane', bad.name.full); // Walter White is insane In the above example, the property would not have a setter. To have a setter for this virtual, do this: personSchema.virtual('name.full').get(function () { return this.name.full; }).set(function(name) { var split = name.split(' '); this.name.first = split[0]; this.name.last = split[1]; }); Documentation

Categories : Node Js

why mocha assertion fails on mongoose.Schema.objectId?
So mongodb ObjectIds in javascript are sadly frustrating in this regard. They are distinct objects resulting in obj1 === obj2 evaluating to false even though the value they represent is identical. There are 3 options: Convert to strings before comparing. I use this a lot because it's so frustrating otherwise. Use the .equals() method they provide: assert.ok(model.organizationId.equals(objId)) Write a custom comparison function that can take null, ObjectIds, or Strings and do the right thing (I've also done this)

Categories : Node Js

Why doesn't my Mongoose schema method "see" my required object?
I believe the issue is that you've created a circular dependency. Story executes require(config.models) which requires Story again inside index.js. Rather than storing a string and requireing it everywhere, try storing the models directly in config.models: config.js module.exports = { test: 'test', models: require(__dirname + '/models') };

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

DIfference between sub docs and population in Mongoose and doubts about database schema
In answer to part one, the difference is that in a Document-Subdocument scenario the subdocument is stored with the document (as a child document, accessible through the use of dot notation). In the Mongoose populate scenario, a reference is held to a document in another collection. When you tell mongoose to populate what it does is make another query to MongoDB to get this 'subdocument'. The main difference I see is that with the mongoose populate method you cannot query for documents using the 'subdocument' properties, whereas you can with the embedded subdocument model. Edit, subdocument example So in MongoDB you can store the data as nested subdocuments like so: { _id: acbdbd, "property": "value", "subdocumentproperty" : { "param1": 1, "param2": 2

Categories : Mongodb

Saving mixed schema in mongoose (markModified doesn't seem to work)
The save method is asynchronous, which means you can't be sure it has finished its work the way you write your code now. Use callbacks: results[0].save( function(error){ if (error){ // augh! }else{ console.log(results[0]); // <- yay! the document is definitely saved here // ... } }); //console.log(results[0]); // <- no, we can't be sure results[0] is already saved in this line

Categories : Mongodb

Mongoose ignoring part of object unless defined as Schema.Types.Mixed
The type property of attr is likely tripping up Mongoose to thinking attr is a string instead of an embedded object. Use a more explicit definition for the property, like this: attr: appearance: String aroma: String flavor: String from: String grade: String lineage: String name: String overall: String packaging: String pickupdate: String price: String reason: String story: String type: type: String

Categories : Javascript

opencv error: assertion failed (size.width>0 && size.height>0) in unknown function line 261
(size.width>0 && size.height>0) means that there is an empty Mat over there. In this case, it must be that image is empty because the camera couldn't be opened. Check VideoCapture::open return value.

Categories : C++

Can't add keys with dots (key paths) to a Mongoose field with type: Schema.Types.Mixed
Yes, it is. Valid JSON doesn't have dots as far as I know. What you are supposed to do is this: { "character": { "treasure_chests": 1 } } Here is an example: JSON Schema example

Categories : Json

EJB unknown abstrat schema but it exists in the DB
em.createQuery() expects a JPQL query, not a SQL query. SQL and JPQL are not the same language. SQL works with tables and columns. JPQL works with entities, fields/properties and associations. NEVER with table and column names. The syntax is similar, but different. Your entity is named Newsletter, but your query uses NEWSLETTER. Class names are case sensitive.

Categories : Mysql

Sql Server 2008 R2 - Shredding XML with unknown Schema
I don't think that is possible to do in SQL without make huge strings manipulations to gather the schemas, and then using dynamic SQL to extract the data. if you can change the XML schema to be generic something below, then parsing from in SQL will be piece of cake: Option 1: <xml> <response ResponseID="1"> <Question QuestionID="1" QuestionTagID="1" ResponseValue="Yes" QuestionTagValue="99" /> <Question QuestionID="2" QuestionTagID="3" ResponseValue="Perhaps" QuestionTagValue="91" /> </response> </xml> Option 2: <xml> <Response ID="1"> <Question ID="1"> <ResponseValue>Yes</ResponseValue> <QuestionTagID>1</QuestionTagID> <QuestionTagVa

Categories : Sql Server

Glassfish Deployment: Unknown Schema Version 2.2
The xmlns in your faces-config.xml is wrong. Try this: <faces-config xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-facesconfig_2_2.xsd" version="2.2"> </faces-config> But if you have look at this question you'll see that JSF 2.2 is not fully supported on Glassfish 3.

Categories : Java

Getting unknown database exception while creating schema programmatically?
You need to add one more property in your hibernate config file, to create the database/schema automatically: <property name="hibernate.hbm2ddl.auto">create</property>

Categories : Java

RangeError: Maximum call stack size exceeded Nodejs mongoose
This line: setTimeout (testCUPwrite (i), 1); is not doing what you think it is. That's directly executing the testCPUWrite function in the current stack. It's not using setTimeout like you think. Something like setTimeout(testCUPwrite.bind(null, i), 1); Might get you going.

Categories : Node Js

unknown vector size python
Try numpy. It is a python bindings for high-performance math library written in C. I believe it has the same concepts of matrix slice operations, and it is significantly faster than the same code written in pure python (in most cases). Regarding your example, I think the closest would be something using numpy.mean. In pure python it is hard to calculate mean of column, but it you are able to transpose the matrix you could do it using something like this: # there are no builtin avg function def avg(lst): return sum(lst)/len(lst) rows = list(avg(row) for row in a)

Categories : Python

How do I get the first X elements of an unknown size NSArray?
You could do this... NSArray *smallArray = [largeArray subarrayWithRange:NSMakeRange(0, MIN(x, largeArray.count))]; That will take the first x elements or the full array if it's smaller than x. If largeArray.count is 100. If x = 110 then it will take the first 100 results. If x = 90 then it will take the first 90 results. Yep, that works :D

Categories : Objective C

C++: accessing an array of unknown size by using try/catch
Accessing an array beyond its bounds gives undefined behavior not an exception. An Undefined behavior means that the program ceases to be a valid C++ program and may show any behavior, correct or incorrect but you cannot rely on it to be consistent. You need to keep track of the size by yourself and loop by using that size or throw an exception as you might want to.

Categories : C++

Passing a std::array of unknown size to a function
Is there a simple way to make this work, as one would with plain C-style arrays? No. You really cannot do that unless you make your function a function template (or use another sort of container, like an std::vector, as suggested in the comments to the question): template<std::size_t SIZE> void mulArray(std::array<int, SIZE>& arr, const int multiplier) { for(auto& e : arr) { e *= multiplier; } } Here is a live example.

Categories : C++

Store unknown size data to table
One approach would be to build two tables, and leverage VARCHAR(MAX): CREATE TABLE table1 (ID INT PRIMARY KEY IDENTITY(1, 1), Name VARCHAR(1024) NOT NULL); CREATE TABLE table1Text (ID INT PRIMARY KEY, data VARCHAR(MAX) NOT NULL); and the ID in table1Text is a foreign key reference to table1. The benefit of this approach is that you can still index table1 and you can provide full-text searching on table1Text without ever having any issues of each table affecting one another.

Categories : C#

Replacing an unknown pattern size with a character
It is possible: inputString.replaceAll("(.)\1+", "$1") Match one character, capture it, repeat it once or more, replace with only the capture. However this may not be the faster solution. Such a thing is also doable with a simple loop: public String removeRepetitions(final String input) { if (input.isEmpty()) return input; final int len = input.length(); final StringBuilder sb = new StringBuilder(length); char current = input.charAt(0); char c; sb.append(current); for (int i = 1; i < len; i++) { c = input.charAt(i); if (c != current) { sb.append(c); current = c; } } return sb.toString(); }

Categories : Java

is it true to do this to malloc array with unknown size
sizeof(int) will return you 4 (and note that few compilers/settings may say you 2 or 8 in response). So your code is equivalent to allocating a 4 bytes long array. If you want an array with unknown size, it could be worth to take a loot at STL containers like std::vector (because it will manage allocations and resizes behind the scene). If you plan to stick with "plain C" scope, you may be interested with TSTL2CL library: http://sourceforge.net/projects/tstl2cl

Categories : C

MatLab memory allocation when max size is unknown
What I recommend doing, if you know the number of lines and can just guess a large enough number of acceptable columns, use a sparse matrix. % create a sparse matrix mat = sparse(numRows,numCols) A sparse matrix will not store all of the zero elements, it only stores pointers to indices that are non-zero. This can help save a lot of space. They are used and accessed the same as any other matrix. That is only if you really need it in a matrix format from the beginning. If not, you can just do everything as a cell. Preallocate a cell array with as many elements as lines in your file. data = cell(1,numLines); % get matrix from line for i = 1:numLines % get matrix from line data{i} = lineData; end data = cell2mat(data); This method will put everything into a cell array, which

Categories : Matlab

Progress bar for unknown Rally query size
The best way to determine if a Rally App is partially complete would be to determine what percentage of pages Rally had returned. Since we limit the size to 200 objects per page you can get a decent estimate of your progress for long running queries based upon those pages.

Categories : Javascript

Haskell unknown size list comprehension
Using recursion inside list comprehension itself: import Data.Maybe basedOn :: Int -> Int -> Bool basedOn a b = even (a+b) func :: [[Int]] -> [[Int]] func a = myFun a Nothing where myFun :: [[Int]] -> Maybe Int -> [[Int]] myFun [] _ = [[]] myFun (xs:xss) j = [[a] ++ b | a <- xs, b <- myFun xss (next j a), pred j a] where pred Nothing _ = True pred (Just x) a = a `basedOn` x next Nothing a = Just a next (Just x) a = Just (x+a) main = putStr $ show $ func [[1..5] , [6..10], [11..15]]

Categories : Haskell

Passing an array of unknown size of structs from c# to c++ dll and back
I'm not an expert (by any means) in C# but the C++ part gets passed a pointer to Tri-struct, which in C++ can be used like an dynamic array you allocate and fill that correctly but you don't have a way to get it back, because from C-perspective you'd need to modify the caller's (C#) pointer but you only get a copy and not a reference to the original. In C++ the closest thing to what you are tying to do, would be to change the prototype to void Dll_TriArray(Tri *&tri) (call by ref, not call by copy) but I'm not sure how to interface that with C# (probably Dll_TriArray(ref triArray); ).

Categories : C#

How to return a byte array of unknown size from method
You are working on a microcontroller with just a little bit of RAM. You need to carefully evaluate if "unknown length" also implies unbounded length. You cannot deal with unbounded length. Your best approach for reliable operation is to use fixed buffers setup for the maximum size. A common pattern for this type of action is to pass the buffer to the function, and return what has been used. Your function would then look much like many of the C character string functions: const size_t HEX_PARSER_MAX_DATA_SIZE = 20; byte data[HEX_PARSER_MAX_DATA_SIZE]; n = oHexP.getParsedData(data, HEX_PARSER_MAX_DATA_SIZE); int HEXParser::getParsedData(byte* data, size_t sizeData) { int dataIndex = 0; // fetch data, do stuff // etc, etc... data[dataIndex] = incomingByte; dataIndex++; i

Categories : C++

Passing a struct containing an int array of unknown size from c# to c and back
First of all change the C++ code to use only one level of indirection: extern "C" __declspec(dllexport) void Dll_TestArray(TestStruct &testStruct) { const int num = 15; testStruct.num = num; testStruct.intArray = new int[num]; for (int i=0; i<num; i++) testStruct.intArray[i] = i+1; } On the C# side you want this: public struct TestStruct { public int num; public IntPtr intArray; } [DllImport("testing.dll", CallingConvention=CallingConvention.Cdecl)] static extern void Dll_TestArray(out TestStruct testStruct); public GetArray() { TestStruct testStruct; Dll_TestArray(out testStruct); int[] arr = new int[testStruct.num]; Marshal.Copy(testStruct.intArray, arr, 0, arr.Length); // need to call back to DLL to ask it to deallo

Categories : C#

Is it possible to create an array on the stack, if its size is unknown at compile time?
Yes, where/when this is allowed (it's not actually allowed in C++, though gcc allows it as an extension) myArray will be allocated on the stack. The implementation is pretty simple: choose the size and subtract it from the stack pointer. As mentioned, C++ doesn't currently allow this, but a proposal for a dynarray class that will allow it has been accepted into the working paper for C++ 14, so something similar will (probably) be allowed soon (if your compiler doesn't already -- some may easily do so, though I've never tested for it).

Categories : C++

Update the preferredMaxLayoutWidth for a multiline UILabel with unknown size (Auto Layout)
Without seeing all the constrains you have setup for your custom view, and the superview that contains it, it's really hard to determine the problem, I suggest you to print out all the view frames of the entire view hierarchy starting from the view controller's view at viewDidLayoutSubviews and determine if the label and its superviews have correct frame set. I have an encountered similar issues with dynamic label size and scroll view so I created a prototype here, might be useful to you too: https://github.com/briandotnet/AutoLayoutScrollViewExperiment

Categories : IOS

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

Adding subdocuments in a document
Array operations work fine: db.document.insert({'_id':99999}) db.document.update({'_id':99999},{$push:{'student':{'name':'Jack','marks':90}}}) db.document.update({'_id':99999},{$push:{'student':{'name':'Jill','marks':75}}}) Now db.document.findOne({_id: 99999}) will give you { "_id" : 99999, "student" : [ { "name" : "Jack", "marks" : 90 }, { "name" : "Jill", "marks" : 75 } ] } Error on $push means that you already have that field in your document and it's not an array. For example, the following code will give you an error on $push db.document.insert({'_id':99998,'student':{'name':'Jack','marks':90}}) db.document.update({'_id':99998},{$push:{'student':{'name':'Jill','marks':75}}}) and the following code will not db.document.inse

Categories : Mongodb

Query for any nested subdocuments
MongoDB doesn't support any sort of wildcard property like you're trying to do here with $. However, you can search multiple properties using an $or operator: db.inventory.find({ $or: [ { product_types.type_1.price: 100 }, { product_types.type_2.price: 100 } ]}) But this is going to return the matching documents in full rather than just the matched array elements, so you'll also have to post-process the docs in your code to pull those out.

Categories : Mongodb



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