Check if PouchDB database is empty - javascript

I am working on an app which stores data locally using PouchDB. It displays a list of items and I would like to be able to check if the database is empty so that in the case that it is, I can append a line 'Your list is empty' to the DOM. Is there a way to do this?

There are several ways to do this. You could query and check for an empty result list. You can also use db.info().
db.info().then(function (result) {
if(result.doc_count === 0) {
console.log('It's empty!');
}
});

Related

Using ExpressJS, how do I extract different data from a SQLite table using the URL?

I want to access resources from a SQLite database table. I have one table for accounts, one for movies and one for reviews. The reviews-table is constructed like this:
CREATE TABLE IF NOT EXISTS reviews (
id INTEGER PRIMARY KEY,
authorId INTEGER,
movieId INTEGER,
review TEXT,
rating INTEGER,
FOREIGN KEY('authorId') REFERENCES 'accounts'('id'),
FOREIGN KEY('movieId') REFERENCES 'movies'('id')
)
What I want to do is that I want to be able to get all reviews, made by one author. But I also want to be able to get all reviews, made for the same movie. Below is my code for getting all reviews made by the same user/author. The code looks the same when getting the reviews based on the movie, with a few changes.
Both of them does what I want them to do. But of course only the one written first in the file are running.
const authorId = request.params.authorId;
const query = "SELECT * FROM reviews WHERE authorId = ?";
const values = [authorId];
db.all(query, values, function (error, review) {
if (error) {
response.status(500).end();
} else if (!review) {
response.status(404).end();
} else {
response.status(200).json(review);
}
});
});
The url will look the same no matter which of them I want running; http://localhost:3000/reviews/3. How can I differentiate the url so that they know which one should run?
I have tried to experiment with query strings, but I'm not sure how that works, and after hours of searching for something that worked on my code, I gave up.
I have also been thinking about using something like
app.use(function (request, response, next) {
if (request.method == "GET" && request.uri == "/reviews/:authorId") {
response.send("Hello World");
} else {
next;
}
});
This didn't work, and it didn't work if I tried to remove ":authorId" from the url either. The page just keeps loading.
So how do I solve this?
The most dynamic would be a single route /reviews and use the query string with the params like ?author=123 or ?movie=123, they can be combined like ?author=123&movie=123. As you want to return JSON the code will be used via API, so the pretty path is usually not as important as when it is a web-url. To make the implementation effective, most people use a function where you can drop the query object in and get the where-clause, or use an ORM.
In express, when you have routers like '/reviews/:authorId' and then '/reviews/:movieId', then the second one will never be called, because the first one will always match. That is something to be careful about when organizing your express routes.

Way to protect documents to never be shown in query results

I would like to have a middleware that based on a condition protects or hides a document from any kind of indexing or querying. for example consider this pseudo code:
Schema.pre('any query',function(next){
if(document.status !== 'published') document.allowQuering = false;
}
or:
Schema.pre('save',function(next){
if(this.status !== 'published') this.allowQuering = false;
}
and this should make sure that those documents without status of published will not show in queries or populate from other documents etc.
I don't think there is such a way.
You can have another collection where you can store the documents which should not be displayed. Later when condition satisfied, you can move that document to the original collection.
if you are using mongoose use select property but beware it will not work with
aggregation for aggregation you should always create a helper method
password: { type: String, select: false }

How can I add fields to a json file from the fields in the front end in a react application?

I have a config.json file where I have the values for the dropdown on the home page of my application. The values are been populated dynamically, now what i am trying to do is enable the user to add values to the config file from the text fields present in the front end. I am posting a request and have been able to push the values to the config file as well but I am unable to handle the condition where the dropdown values are already present. I have three fields Controller, test and Protocol and I want to apply the logic which is commented in the server side code which I have shown below. Can anyone please help to achieve this logic. Any help is much appreciated.
Regards
Part where help is needed to build the logic.
// We found controller so need to check for test
// if test found nothing to do
// if not found add test
// if test found need to check for protcol
In your config.json, Test is an array of elements. Hence d.Test === req.body.test will not yield the intended result. I assume you're trying to check whether req.body.test is present in the Test array, and not if they match.
const { controller, test, protocol } = req.body;
const index = config.controllers.findIndex((c) => c.Name === controller);
if (index === -1) {
config.controllers.push({
Name: controller,
Test: [test],
Protocol: [protocol],
});
} else {
// Check if test exists in Test array...
if (!config.controllers[index].Test.includes(test)) {
config.controllers[index].Test.push(test);
} else {
// Check if protocol exists in Protocol array...
if (!config.controllers[index].Protocol.includes(protocol)) {
config.controllers[index].Protocol.push(protocol);
}
}
}
// Rest of your code.
BTW, it is a good idea to destructure res.body and the values in variables, will help you write cleaner looking code. Hope this helps!

Dynamoose/DynamoDB update saving empty array as null

I'm using the Node.js package Dynamoose to handle DynamoDB requests in my web application.
Problem is when I try to update the item whenever the JSON object includes an empty array Dynamoose seems to set that to null. Or it could be DynamoDB for all I know.
Below is part of my schema that I'm using for this table.
var NoteSchema = new dynamoose.Schema({
_id: String,
details: Array
});
In the code below the variable body is set to {details: []}. I have confirmed this by running console.log(body);.
Note.update({
_id: searchid
}, body, function(err, note) {
if (err) {
console.log(err);
} else {
console.log(note);
}
});
Problem is inside that callback function when running console.log(note); details doesn't even show up at all. So it's null or undefined. In the Amazon Web Services again details doesn't exist at all for that entry.
What is so strange is when creating a new Note, setting details = [], and saving that, details is an empty array and works perfectly. So to me it seems like a specific problem with updating the record and setting that property to an empty array, since creating a record and setting that property to an empty array works perfectly.
How can I update the record and set details to an empty array?
Figured this out. Submitted this issue to the GitHub repo. Basically the following line (lib/Model.js about line 396) of code checks to see if the value is an array with length = 0. If so it will delete that JSON key before sending it to AWS.
if(val === null || val === undefined || val === '' || (Array.isArray(val) && val.length === 0)) {
I submitted a pull request using my fork. In that pull request I made the change to allow an optional JSON object parameter of options to be passed into the update function. This is the 3rd parameter of the update function and right before the callback function. If there is a key called emptyarrayallowed and that value is set to true then you that line above will get changed into the following.
if(val === null || val === undefined || val === '') {
For example in my example above changing the update function to the following will work (as long as you are using my fork or the pull request has been approved).
Note.update({_id: searchid}, body, {"emptyarrayallowed": true}, function(err, note) {
if (err) {
console.log(err);
} else {
console.log(note);
}
});
Let me know if you have any questions regarding this solution.
Small update on Charlie's answer. The functionality was merged as mentioned by Charlie. However, looks like the property name was renamed to allowEmptyArray from emptyarrayallowed.

How to query orchestrate.io

I was searching for an easy and simple database for a little highscore system for a some games I'm developing in javascript.
I saw Orchestrate.io in github's student developer pack. I found a suitable drivermodule nodejs orchestrate and have integrated them.
The problem comes with querying orchestrate for my data. I have managed saving scores and querying them with db.list('collection'), but this seems to not responding with all data. It appered to me that some values are not returned.
I read about the db.search('collection','query') function. But I don't really understand how I could return all data because I don't want to query in a specific way.
My objects are as simple as follows:
{"name":"Jack","score":1337}
As I understand, one has to send a key, when putting such values to an orchestrate-collection. But I'd like to query the whole collection and get the values in a descendant order in regard to the score.
As for now I end up sorting the result on the client-side.
I hope you guys can give me some hints for a query that can sort for specific values!
You have the option to use a SearchBuilder
db.newSearchBuilder() //Build a search object
.collection('collection') //Set the collection to be searched
.sort(score, 'desc') //Set the order of the results
.query("*") //Empty search
.then(function (res) { //Callback function for results
//Do something with the results
})
Source
By default, .list uses a pagination limit of 10. You can either increase that, e.g.:
db.list('collection', { limit: 100 })
Or use .links, .links.next (from the docs):
db.list('collection', { limit: 10 })
.then(function (page1) {
// Got First Page
if (page1.links && page1.links.next) {
page1.links.next.get().then(function (page2) {
// Got Second Page
})
}
})

Categories

Resources