Facing issue with regex in node.js - regex

I want to execute a query just like wild card search in sql.So I use regex in nodejs and mongoose.When I use hard code then its works but when I put in variable it wont work.Where is the issue.
Code with hard code
AlertModel.find({"alertName":{$regex: /.*RTE.*/}}).lean().exec(function (err, result) {
if(err)
{
console.log(err);
}
else
{
return res.status(200).send(result);
}
});
But in case of using variable it wont work
var regFiled='/.*RTE.*/';
AlertModel.find({"alertName":{$regex:regFiled}}).lean().exec(function (err, result) {
if(err)
{
console.log(err);
}
else
{
return res.status(200).send(result);
}
});

You're using a variable with a string value instead of a RegExp literal.
Change
var regFiled='/.*RTE.*/';
to
var regFiled=/.*RTE.*/;
and it should work like the hard-coded version.
Or if regFiled really is meant to hold a string form of the expression, you can convert it to a RegExp object with:
{$regex:new RegExp(regFiled)}

Related

Flutter FireStore empty list

I'm trying to read the ID of each doc in a collection. As I can saw, doc.id is a string, and it has the value name for each doc. So I just tried to add that value to a list, for later pass it to a DropDownButton. But for some reason, the list return null.
List<String> readthishit() {
List<String> ex;
FirebaseFirestore.instance
.collection('Enrollment')
.get()
.then((QuerySnapshot querySnapshot) => {
querySnapshot.docs.forEach((doc) {
ex.add(doc.id);
})
});
return ex;
}
What's happening?
You need to use the await keyword & wait for the result from Firebase.
Currently, you are sending a call to the Firebase but, before the result from Firebase, your code is returning the null list ex.
Future<List<String>> readThisShit() async {
List<String> ex = <String>[];
final querySnapshot = await FirebaseFirestore.instance
.collection('Enrollment')
.get();
querySnapshot.docs.forEach((doc) {
ex.add(doc.id);
});
return ex;
}
Also, I think you should use lowerCamelCase notation for your method names. So, readthisshit will become readThisShit.

Regex for Mongo db from node.js is not working

I am using regex to fetch data from mongodb from my node js application which is not working. Here is the code snippet. the query can not match with the set of records.
var analysis_date = '/^'+moment(fromTime).format('YYYY-MM').toString()+'/';
user_analysis.find({
parent_id: usrId,
analysis_date: {
$regex : analysis_date
}
},function(err, result) {
//some Code goes here});
Instead of specifying the regular expression as a string, try passing a RegExp object:
user_analysis.find({
"parent_id": usrId,
"analysis_date": new RegExp(analysis_date, 'i')
}, function(err, result) {
// ...
});
If you want, you can also pass a string, but then you'll need to remove the / delimiters:
user_analysis.find({
"parent_id": usrId,
"analysis_date": {
$regex: '^' + moment(fromTime).format('YYYY-MM').toString(),
$options: "i"
}
}, function(err, result) {
// ...
});

Loopbackjs: Cannot cancel a hook (ie: beforeSave)

Actually I'm trying to cancel a hook to avoid duplicate pair entity-name/subname - by a server-side check.
My example is, if an entity already exists with the same name and subname, I'd like it not to be created/persisted.
Here's my code so far in my entity.js:
module.exports = function (ContactType) {
ContactType.observe('before save', function filterSameEntities(ctx, next) {
if (ctx.instance) {
ContactType.find({where: {name: ctx.instance.name, subname: crx.instance.subname}}, function (err, ct) {
if (ct.length > 0) {
//I'd like to exit and not create/persist the entity.
next(new Error("There's already an entity with this name and subname"));
}
});
}
next();
});
};
Actually the error is correctly displayed, but the entity is still created and I would like that it wouldn't be the case.
Your last next(); statement is always called, hence the save-action always happens.
You can end further execution using return.
Keep in mind that .find() is async, so just adding return inside the callback would still cause that last next(); statement to run.
Please try this:
module.exports = function (ContactType) {
ContactType.observe('before save', function filterSameEntities(ctx, next) {
if (!ctx.instance) {
return next();
}
ContactType.find({where: {name: ctx.instance.name, subname: ctx.instance.subname}}, function (err, ct) {
if (err) { // something went wrong with our find
return next(err);
}
if (ct.length > 0) {
//I'd like to exit and not create/persist the entity.
return next(new Error("There's already an entity with this name and subname"));
}
return next();
});
});
};

How to update warning in webstorm?

I've been developing node js app which use mongodb to manipulate static data. I'm using webstorm to my main editor program.
I wrote a function which use mongodb to find a data. Actually, this is sample code in the mongodb's getting started document.
var findRestaurants = function(db, callback) {
var cursor =db.collection('restaurants').find( );
cursor.each(function(err, doc) {
assert.equal(err, null);
if (doc != null) {
console.dir(doc);
} else {
callback();
}
});
};
In the 3rd line, each is the method of the cursor object which defined in mongodb driver api. This method operate the callback function to the returned records which the cursor pointing to, and there's no problem to run this code.
But, in the webstorm editor window, the program gives warning to each method, saying that this symbol is deprecated. It says that javascript has deprecated this each method. It may seems that webstorm doesn't know about the api information of node js or mongodb. Of course, I could ignore this message, but it makes me a little irritated.
Is there a way to update warning information of webstorm program? I think that there's a way to register node js or mongodb api list to webstorm program, but I can't find it by searching.
Thanks.
I was experiencing this same problem, and I have found it to be a reference to the javascript .each() method which is in fact deprecated. The simplest (read quick fix) way to resolve this, is to place "//noinspection JSDeprecatedSymbols" above the line giving the error. You can alternatively click on the lightbulb icon on the left, goto "inspection Deprecated Javascript symbol options", then Suppress for statement (or any other option you may wish to use to disable this warning)
var findRestaurants = function(db, callback) {
var cursor =db.collection('restaurants').find( );
//noinspection JSDeprecatedSymbols
cursor.each(function(err, doc) {
assert.equal(err, null);
if (doc != null) {
console.dir(doc);
} else {
callback();
}
});
};
I took a look at the list of functions present in MongoDB engine for Node.JS. There two function that can replace "each" function: "next" and "hasNext".
So for your example, I would write this code:
var findRestaurants = function(db, callback) {
var cursor = db.collection('restaurants').find( );
var parseRestaurant = function() {
cursor.next(function(err, restaurant){
if (err)
return console.error(err);
console.dir(doc);
hasNextRestaurant();
});
};
var hasNextRestaurant = function() {
cursor.hasNext(function(err, result){
if (err)
return console.error(err);
if (result)
parseRestaurant();
else {
//Here is the last point of iterations
//We can use this for statistics output
return console.log('That\'s all');
}
});
};
hasNextRestaurant();
}
Or something like this:
var findRestaurants = function(db, callback) {
var cursor = db.collection('restaurants').find( );
var parseRestaurant = function(err, doc) {
if (err)
return console.error(err);
console.dir(doc);
cursor.hasNext(checkNext);
};
var checkNext = function(err) {
if (err)
return console.error(err);
if (result)
parseRestaurant();
else {
//Here is the last point of iterations
//We can use this for statistics output
return console.log('That\'s all');
}
cursor.next(parseRestaurant);
};
cursor.hasNext(checkNext);
}

Firebase python - How to check if field (property) exists in doc

We have read a document from firebase using Python.
doc_ref = db.collection(u'collection_name').document(collection_abc)
doc_fetched = doc_ref.get()
if (doc_fetched.exists):
if (doc_fetched.get('doc_field')):
We get the following error
KeyError("'doc_field' is not contained in the data")
How do we check if doc_field exists in doc_fetched? This document might have some fields populated, and some not populated at the time of read (by design).
We also tried the following with the same error.
if (doc_fetched.get('doc_field') != null):
As you can see from the API documentation for DocumentSnapshot, there is a method to_dict() that provides the contents of a document as a dictionary. You can then deal with it just like any other dictionary: Check if a given key already exists in a dictionary
To solve this, you can simply check the DocumentSnapshot object for nullity like this:
var doc_ref = db.collection('collection_name').doc(collection_abc);
var getDoc = doc_ref.get()
.then(doc => {
if (!doc.exists) {
console.log('No such document!');
} else {
if(doc.get('yourPropertyName') != null) {
console.log('Document data:', doc.data());
} else {
console.log('yourPropertyName does not exist!');
}
}
})
.catch(err => {
console.log('Error getting document', err);
});
Or you can use to_dict() method as in the #Doug Stevenson answer