Mongoose find query passing variables [duplicate] - node.js

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

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

push array in array field in mongodb [duplicate]

This question already has answers here:
Push items into mongo array via mongoose
(11 answers)
Closed 4 years ago.
I have an array called students in a schema called Course. I created a route that allows me to add students to this array using a student's ObjectID like so:
router.put('/addStudent/:courseID', function (req, res) {
Course.findOneAndUpdate({courseID: req.params.courseID}, {$push: {students: req.body.students}})
.populate('students')
.exec(function (err, course) {
if (err) return res.status(500).send("There was a problem adding this information to the database");
res.status(201).send(course);
})
});
When I try making a PUT request to my endpoint with the following JSON body:
{
"students":["5b1f06cafa355c2d187c344f"]
}
Nothing happens at all, it just sends me back the course with the student ID not added. How do I make it so I could add more student IDs to the array? I don't want it to replace the array with a student ID, I want to keep adding more as I make more requests.
Thanks!
You need to use $each with $push
Course.findOneAndUpdate(
{ courseID: req.params.courseID },
{ $push: { students: { $each: req.body.students } } }
)
Course.findOneAndUpdate(
{ courseID: req.params.courseID },
{ $addToSet: { students: { $each: req.body.students } } }
)
put request will update your db and findOneAndUpdate method from mongoose is also for updating you current item, you need to use post request and save method in mongoose instead if you want create a new item.
You can Try this:
Course.findOneAndUpdate(
{ courseID: req.params.courseID },
{ $push: {
students: req.body.students
}}, options, function(err, values){
});

How to update a specific value in object of MongoDb via Post?

I have a schema with sub objects, i want to be able to update a specific key inside of it. If i update only a specific key - like in the Post example - it's empty all the other keys..
for example :
{
"_id": "32323323",
"names":{
"firstname":"John",
"lastname":"foo",
"workers":{
"position":"manager",
"address":"1 st"
}
}
}
I want to update Only "position" key via Post request , for example :
$.post({
url: 'workers/information/',
data: {
user_id: user_id,
names: {
workers: {
position: some data,
}
}
},
success: function (result) {
alert('Your information updated successfully')
}
});
Here is the update method in NodeJs server :
UserDataController.updateWorkersInformation = function (userID, workersInformation, cb) {
if (userID) {
user.findOneAndUpdate({_id: userID}, workersInformation, function (err, result) {
if (err) return cb(err);
return cb(null, result);
});
}
};
You may want to look into mongoose. It provides a more simple interface than the native client does.
https://www.npmjs.com/package/mongoose
However, as the comment mentioned, you are missing the $set operator. {$set:workersInformation}
If update is called without the $set operator, the entire document will be replaced with your update object.
http://mongodb.github.io/node-mongodb-native/2.2/tutorials/crud/

Mongoose: How to get latest collection data? [duplicate]

This question already has answers here:
How to get the latest and oldest record in mongoose.js (or just the timespan between them)
(8 answers)
Closed 5 years ago.
I am trying to get the latest collection record from my MongoDB using mongoose.
My current code goes as follows:
ApiData.findOne(
(err, data) => {
if (err) {
// res.status(200).send(err);
}
if (data) { // Search could come back empty, so we should protect against sending nothing back
// res.status(200).send(data);
console.log(data);
} else { // In case no kitten was found with the given query
// res.status(200).send("No kitten found");
}
}, { sort: { _id: -1 }, limit: 1 });
But this does not work in sorting the latest data, only shows the first record.
To get latest added data :
ApiData.findOne({}).sort({date: -1}).exec(function(err, data) {
if (err) {
// res.status(200).send(err);
}
if (data) { // Search could come back empty, so we should protect against sending nothing back
// res.status(200).send(data);
console.log(data);
} else { // In case no kitten was found with the given query
// res.status(200).send("No kitten found");
}
});
To get all data just replace findone with find
I found out my problem after searching Stackoverflow.
The problem was fixed by removing , { sort: { _id: -1 }, limit: 1 }); and adding .sort.({"_id": -1}) to the end of my closing brackets!
Thanks for trying to answer my problem guys!

Fetch entries from mongodb using mongoose

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

Resources