Fetch entries from mongodb using mongoose - node.js

I am using mongoose to operate mongodb in node. And now I have to query entries from Post table where tags doesn't contain any tag like inc:___, inc:gdc, exc:abc, exc:57uyht7, all others tags are allowed like(test,card,check).
PostModel.Post.find({
$where:this.activeFlag==true && (this.tags!= null && this.tags != /^inc:/ && this.tags !=/^exc:/)
}), function(err, stack) {
if (!err) {
logger.debug('Posts found successfully.');
} else {
logger.error('Problem in finding posts, error :' + err);
}
});
But this is not working.. My query fetches entries with inc:dbgh also.
Can anyone help me?
Thanks in advance.

According to Mongo docs, you should pass either a string or javascript function to $where, and you pass javascript expression, which gets evaluated in place.
Also, your query can be simplified to
PostModel.Post.find({
activeFlag: true,
tags: {
$exists: true,
$not: /^(inc:|ecx:)/
}
}, function(err, stack) {
if (!err) {
logger.debug('Posts found successfully.');
} else {
logger.error('Problem in finding posts, error :' + err);
}
});

Related

mongoose: findOne using mongo _id

I get that this can be a duplicated question. I looked up at least 10 related questions and answers, but I am still not able to find the document.
I am trying to get the document using .findOne(). I have the _id that created by MongoDB. But, I get null for every search I try.
await mongoose.connection.db
.collection('testing')
.findOne({ _id: req.body.test_id }, (err, result) => {
if (err) {
res.status(400);
} else {
console.log(`whaaaaaahsidufh ${result}`);
}
});
I tried _id: mongoose.Type.ObjectId(req.body.test_id) and other possible way to search. How can I retrieve the result by using _id on mongoose?
you can use findById();
try {
const test = await mongoose.connection.db.collection('testing').findById(req.body.test_id);
if (test ) {
console.log(`whaaaaaahsidufh ${test}`);
} else {
console.log(`test not found`);
}
}catch(err){
res.status(400);
}

Mongoose find query passing variables [duplicate]

This question already has answers here:
How to query nested objects?
(3 answers)
Closed 5 years ago.
everyone hoping to all are fine. I'm new to node.js and mongodb and i'm having trouble passing in variables to a mongoose model query.
When I pass two arguments, its result is empty and however the record exists.
Retrieving data from MongoDB Image
Sending Get Request through Postman
GET Route: /data/:vehicle_no/:drive_id
URL: http://localhost/api/data/ZXC-1123/drive_234
Route Code:
var reg_no = req.params.vehicle_no;
drive_id: req.params.drive_id;
vehicle.find({
ID: reg_no,
Trip_Details: {
FileName: drive_id
}
}, function(err, result) {
if(err) {
res.json(err);
} else if(result.length > 0) {
res.json("Drive id Found");
} else {
res.json("Drive id not Found");
}
})
Result: Drive id not found
However Expected Result must be: Drive id found
In the above code: Trip_Details is the objects array having file_name, _id, TripData.
And If I pass only one argument like
vehicle.find({ ID: reg_no }
then result found.
Kindly help,
Thanks in Advance
To query based on two parameters, you can also use $and for better readability.
The place where you went wrong is in writing query, second parameter should be written as :
vehicle.find({
ID: reg_no,
Trip_Details.FileName: drive_id
}
Your implementation using $and will be as follows:-
vehicle.find({
$and: [
{ID: reg_no},
{Trip_Details.FileName: drive_id
}]
}, function(err, result) {
if(err) {
res.json(err);
} else if(result.length > 0) {
res.json("Drive id Found");
} else {
res.json("Drive id not Found");
}
})
For more information refer Mongoose Docs

Node.js : Mongodb - Concurrent Requests

In my node.js application, a route is executed on Ajax request and it always receives concurrent requests.
My requirement is to check for a similar document and if exist upsert the data to existing document. If no similar document then create a new record.
Refer the code given below. The problem is that most times the "findExistingDoc" returns false, but by the time when a call tries to create a new document, a similar document is already created by a previous call.
Please help with a optimal solution to solve this problem.
self.findExistingDoc(function(err, doc){ // Check if a similar doc already exist
if (!doc){
console.log ("NO existing doc");
self.save(function(err, doc) {
if (err) {
console.error ("DB Error while creating new doc : " + JSON.stringify(err));
} else {
console.log ("New document created");
}
});
} else {
console.log ("existing doc");
var qry = {"name": req.s_name, "class": req.s_class};
self.model("Collection").findOneAndUpdate (qry, {$addToSet: {"data": req.body.s_data}}, {safe: true, upsert: true}, function (err, album) {
if (err) {
console.error ("DB Error while adding data to existing doc : " + JSON.stringify(err));
} else {
console.log ("Data added to existing doc");
}
callback(err, output);
});
}
});
Solved my problem after some googling. Thanks to the new "$setOnInsert" operator that's introduced in mongodb v2.4.
var slug = getUniqueSlug("name");
var qry = {"name": req.s_name, "class": req.s_class};
var update = {"$addToSet": {"data": req.body.s_data}, "$setOnInsert": {"slug": slug}};
self.model("Collection").findAndModify ( qry, update, {"safe": true, "upsert": true} );

Mongoose - Increment with findOne

I'm working on some query with Mongoose where I need to skip and limit subdocuments, but in the same query I want to increment some field in document. Currently is my query built with chaining, because I got a lot of problem when I tried to do it just with options. This is what I have:
Model.findOne({ shorten_id: id }).select('title content comments views').slice('comments', [0, 10]).exec(function(err, db_res) { if (err) { throw err; } else { console.log(db_res); } });
I would like to increment filed 'views' for 1 when calling this query, but as I said, I tried a lot of things and it just didn't work.
You can use findOneAndUpdate to modify a document while also fetching one.
Model.findOneAndUpdate({ shorten_id: id }, { $inc: { fieldToIncrement: 1 })
.select('title content comments views')
.slice('comments', [0, 10])
.exec(function(err, db_res) {
if (err) {
throw err;
}
else {
console.log(db_res);
}
});

mongoosejs query fails when filtering using a string of keys as selector

I was attempting to query docs from a mongodb and have the system return only a few fields from the documents matching the query. I first tried the syntax listed below for the first query and it failed to return i.e. the callback was never called.
I then experimented some more with alternative syntax and was able get results from the second query listed below. I'd like to understand why the first query didn't work - have I misinterpreted the syntax?
this is mongoose 3.6.8 and mongo 2.4
TIA
First query
query.find({
category:{
$in: categoryArray
}
,expiration:{$gte: new Date()}
,place:queryVal.destination
}
,'_id expiration url'
,function (err, docs) {
if (err) {
console.log(err);
} else {
console.log('queryJoin returned ' + docs.length + 'entries');
}
}
);
Second query
query.find({
category:{$in: categoryArray}
,expiration:{$gte: new Date()}
,place:queryVal.destination
})
.select({_id:1, expiration:1, url:1})
.exec(function(err, docs) {
console.log('queryJoin returns');
if (err) {
console.log(err);
} else {
console.log('queryJoin returned ' + docs.length + 'entries');
}
});
Your first attempt used Model.find syntax but you were trying to use it with Query#find which doesn't support a fields parameter. As such, Mongoose interpreted your field selection string as a callback which is why your actual callback didn't get called.

Resources