I'm using knex with node and I was thinking of making a field in the migration that would take an array of objects. I know simple stuff like
.string("bla")
.notNullable()
and so on, looking in the documentation can't seem to find it
wanting something like
.array_of_objects //field name
knex.schema.createTable('users', function (table) {
table.increments();
table.string('name');
table.timestamps();
//example
table.array
})
With table.specificType you can create which ever type of database column you like. You need to check from your database, which kind of columns it supports.
It would make easier to answer the question if you could tell what kind of SQL queries you are after. To be able to use knex, you need to know SQL. Knex will never abstract SQL away.
If you are looking for a database library for node.js that abstracts SQL away you might like to checkout sequelize.
Thanks for the post with the specificType. From what I saw PG didn't have an array of objects field, but did have an array of strings field. I ended up taking my array of objects and separating it into two string arrays one named keys and the other values. I stored both of those arrays in the database. Then when I did a get request I took the two arrays joined them together into an array of objects with some javascript tacking. Seems to do the trick.
Related
I am new to NodeJS, MongoDB and express.
I am able to insert, delete and update data but I dont really know how to work with it.
I want to choose some data(e.g. from a dropdown form) and then pass that data to some functions and calculate results. How is it possible to show the results to the client in the webpage(e.g. in a table)?
For example: I have different JSON objects stored in my database and now I want to select one by the name. Then do some calculations with it and show the results to the client.
Also: Is it possible to tell the Database to only accept valid JSON data?
Yes you can get specified data from the database and it will work a lot better with mongoose. You can define schema in mongoose and you can focus more on the data instead of how your data look like. And you can do validation to accept the valid data.
Is it possible to fetch all records of a table in bookshelf without a query?
I'v got a Model named Person, and I'd like to retrieve all of its records.
What I am doing currently is this:
Person.where('id', '>', 0) ).fetchAll()
.then((result) => {
// doing stuff
});
which just doesn't feel right.
I was hoping for something like
// using empty querybuilder
Person.query().fetchAll()
or
Person.all //
Am I missing something?
I suppose model.fetchAll is the thing you are looking for.
Simple helper function for retrieving all instances of the given model.
See the API Reference of Bookshelf.js
In this case, you can use Model.fetchAll(), which fetches a collection of models from the database, using any query parameters currently set on the model to form a select query.
I would like to do more complex queries on jsonb/documents that contain arrays of objects. Is there any library anyone would recommend for Node? I am using pg but I want to do more advanced queries like select the document where a document has an array with an object with a certain key/value. If there aren't any libraries that do this, does anyone know how I could do it with json functions/etc in psql? or point me to a book/resource where I could learn this advanced querying?
If you need to do really complicated things you're going to be writing SQL no matter what. But for basic queries that involve working with JSONB fields Massive (full disclosure, it's my project) has you covered, and executing handwritten prepared statements is as easy as anything else since scripts are loaded into the API.
Searching an embedded array falls into the 'really complicated' category, unfortunately, but if you know your element positions you could do this quite simply with Massive:
await db.mytable.find({
'somejson.arrayfield[0].key': 'value'
});
This would return all records from mytable where the somejson column has an arrayfield array, the first element in which contains a "key": "value" pair.
For searching, check out the Postgres docs. The specific question you have requires a lateral join on the jsonb_array_elements function like so:
SELECT somejson
FROM mytable
JOIN LATERAL jsonb_array_elements(mytable.somejson->'arrayfield') AS elements
ON TRUE
WHERE elements->>'key' = $1;
With Massive, you'd put this query in a script in your application's /db directory and run it as db.myScriptName('value'). You can use folders to group similar scripts too.
I am new to NOSQL and MongoDB, I am building an app with NodeJS and Mongoose, and I am building a mongoose schema for a new collection.
The documents of this collection will have some standard fields (id, creation date, user etc...) but then I need to store other stuff, which is a "data" field which will have to contain different data depending on the document. The value will sometimes be simple text and other times it will have lots of key/values pairs.
I am wondering what would be the best solution for this kind of storing needs :
-Create only one "data" field with a String type and then put different types of data into it (text for simple values, stringified objects for more complex data)
-Create in the model all the possible fields that my "more complex data" could have and use only the ones I need in each document
-Something else
What is the best practice for this kind of thing ?
Try to use the Mixed schemaType, I think that's what you are looking for:
http://mongoosejs.com/docs/schematypes.html
This one:
-Create in the model all the possible fields that my "more complex data" could have and use only the ones I need in each document
Mark the standard fields of the schema as required: true and leave the rest optional. That way you get the flexibility you want without losing the Mongoose benefits of validation, casting, and change detection.
I want to have default values for certain fields in my mongoose models. The trick is I don't want to store these values in the database, but what to add them when the model is initialized.
Please help.
You can define an 'init' middleware function for the schema which runs when a model instance is loaded from the database. That should let you manipulate the instance to add your defaults as needed.
Also see this related question for more details as the docs are pretty spare on this.
Maybe a json file?
Using a require('path/to/json' ) you can acces to it and get the values.
Im actually doing something like that, but using the same JSON SCHEMA wich is build for validation purpose.