Way to protect documents to never be shown in query results - javascript

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 }

Related

exists() function not finding any documents in Firestore Security Rules

So I have a followers collection and a users collection. Creating a doc in the followers collection with a certain ID requires a doc to exist with the same ID in the users collection.
So, in the security rules, I check for the existence of that document.
match /followers/{followers} {
function loggedInUserMatching() {
return (request.auth != null) && (request.auth.uid == followers);
}
function userExistsAndLoggedIn() {
return loggedInUserMatching() && exists(/databases/$(database)/documents/users/$(request.auth.uid));
}
allow create, delete: if userExistsAndLoggedIn();
}
In my tests, I try to create a doc in followers without the corresponding doc in the users collection. This should fail.
const database = testEnv.authenticatedContext('user1').firestore();
let testFollowersDoc = database.collection("followers").doc("user1");
expect(assertFails(testFollowersDoc.set({followers: []}))).resolves.toBeDefined();
Then, I create the doc in the users collection and then try to create the doc in followers again. This should succeed, but it always fails.
const testUserDoc = database.collection("users").doc("user1");
testUserDoc.set({about: "Wow", following: []});
expect(assertSucceeds(testFollowersDoc.set({followers: []}))).resolves.toBeUndefined();
The create rule for the users collection is correct and the document is actually created. I can access its data and verify it exists. But in my security rules, the exists() function always returns false, so the permission is denied and the document is not created.
What could be the cause of this? Am I using the exists() function incorrectly? Or am I not creating the document properly in my test?
I've been trying to solve this for a long time so any help would be appreciated!
These lines are asynchronous and should have await.
expect(assertFails(await testFollowersDoc.set({followers: []}))).resolves.toBeDefined();
expect(assertSucceeds(await testFollowersDoc.set({followers: []}))).resolves.toBeUndefined();

Why is Mongoose returning "null" continuing to return null regardless of what I do?

I am able to connect to my MongoDB database and am sure that I am connecting to the correct one. When I try to get a document from the database I always get "null". I am sure that there are documents in the collection as I can see them in Compass.
const theschema = new Schema({
sensor: {
type: String,
required: true
}
})
const model = mongoose.model('Sensor', theschema)
model.findOne({}, function(err, data) {
console.log(data)
})
Above is the code I am currently using for this. I'd appreciate any help possible. Thanks! :)
I think you need to specifie a condition inside curly brackets. In example: Adventure.findOne({ country: 'Croatia' }, function (err, adventure) {}); .
As you can read in docs Note: conditions is optional, and if conditions is null or undefined, mongoose will send an empty findOne command to MongoDB, which will return an arbitrary document. If you're querying by id, use findById() instead.
You can use to find method if you don't have any query to search for (as per your question) and limit it to some value based on each document size and use case (you can limit it to 1 since you are testing connection it seems)
const sensor = mongoose.model('Sensor', theschema)
let query = sensor.find({}).limit(1);
query.exec(function(err, data) {
console.log(data)
})
Just found the problem. The issue was mongoose pluralises collection names therefore it was looking in the wrong collection.
The solution I used was to add this line of code before defining the model
theschema.set('collection', 'Sensor'). This force sets the collection so Mongoose doesn't pluralise it

How can I check if a data search was successful in Firebase

I am checking if a combination of child values exists in my DB.
This works but can't get the proper message to be displayed in the console.
the correct console message is displayed in both else statements. The one that is not being displayed properly is the console.log('yes').
Or actually it is displayed but always followed by aconsole.log('no') and I have no idea why
There is however a match found because the correct data is shown in console.log(details); console.log(snapshot.key);
FBSearch: function(){
var T1 = this
var T2 = this
var T3 = this
var ref = firebase.database().ref("flights");
ref
.orderByChild('date')
.equalTo(T2.flight.dat)
.on('child_added', function(snapshot) {
var details = snapshot.val();
if (details.flight == T1.flight.flt) {
if(details.origin == T3.flight.org){
console.log(details);
console.log(snapshot.key);
console.log('yes')
} else {
console.log('no')
}
} else {
console.log('no')
}
})
}
The desired outcome is a success message when a match is found
Not sure if this is the answer to your question, but something you might want to consider...
Right now you're reading all flights of the specific date, in an effort to check if one of them exists. This is suboptimal, and can waste lot of your users' bandwidth. Ideally a yes/no question like that should require you to pass in the criteria, and get a minimal yes/no type answer.
While the Firebase Realtime Database doesn't support exists() queries, and can't query on multiple conditions, you can make significant improvements by adding a special property to your data to support this query.
As far as I can see, you're filtering on three properties: date, flight, and origin. I recommend adding an extra property to all flights that combines the values of these properties into a single value. Let's call this property "origin_date_flight".
With that property in place you can run the following query to check for the existence of a certain combination:
ref
.orderByChild('origin_date_flight')
.equalTo(`${T3.flight.org}_${T2.flight.date}_${T1.flight.flt}`)
.limitToFirst(1)
.once('value', function(snapshot) {
if (snapshot.exists()) {
console.log('yes')
} else {
console.log('no')
}
})
The main changes here:
The query uses a composite property as a sort-of index, which allows it to query for the specific combination you're looking for.
The query uses limitToFirst(1). Since you're only looking to see if a value exists, there's no need to retrieve multiple results (if those exist).
The query uses once("value", which allows it to check for both existence and non-existence in a single callback. The child_added event only fired if a match exists, so can't be used to detect non-existence.
And as a bonus, this new property also allow you to for example get all flights out of Amsterdam today:
ref
.orderByChild('origin_date_flight')
.startAt(`AMS_20190728_${T2.flight.date}_`)
.endAt(`AMS_20190728_${T2.flight.date}~`)
.once('value', function(snapshot) {
snapshot.forEach(function(flightSnapshot) {
console.log(flightSnapshot.key+": "+flightSnapshot.child("flt").getValue());
})
})
Also see:
Query based on multiple where clauses in Firebase

Mongo DB - Why my Users.findOne is Undefined?

I'm working on Meteor, trying to find some values from Mongodb collection.
here is the code:
var sameLogins = Users.findOne({login: 'a'});
console.log(sameLogins);
But it's returning and "undefined".
But record exists in collection:
So, can anybody tell what I'm missing?
Also, in mongo console - everything is working fine:
I was looking in Publish/Subsribe stuff, but i'm using autopublish module yet.
Thank you!
I will leave the answer for this issue for new users having the same problem.
If you're using autopublish package then you should be aware that it's publishing the result of .find() for every collection.
But, Meteor.users.find(), be default, will return only _id and profile fields, so documents in your Meteor.users client collection will have these two fields only.
The most easy workaround for this would be to create your own publication (allUsers, for example) and in it to return those fields you need:
Server:
Meteor.publish('allUsers', () => {
// check for Meteor.userId() is omitted, put it here, if needed
return Meteor.users.find({}, { fields: { ... } });
});
Don't forget to subscribe to it:
Client:
Meteor.subscribe('allUsers');
Update for Meteor:
Right now you are storing a cursor in your variable sameLogins. In order to retrieve the results you want, you must actually execute this query by either calling fetch(). What is returned from findOne without fetch is essentially an object that you could use to iterate over and find mongoDB documents - (called a collection cursor). The cursor is not your result itself.
Calling fetch would like something like:
Users.findOne({login: 'a'}).fetch()

Check if PouchDB database is empty

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!');
}
});

Categories

Resources