I am trying to get data from my mongoDB database by using mongoose filters. The scenario is that each user object in the database has certain fields like "Region" or "Sector".
Currently I am getting all the users that contain the keyword "region" in there object like so:
// Filter all healthcare bios by region
app.get('/user',function(req, res) {
// use mongoose to get all users in the database
User.find({region: "NA"}, function(err, user)
{
// if there is an error retrieving, send the error. nothing after res.send(err) will execute
if (err)
{
res.send(err);
}
// return all todos in JSON format
console.log(user);
res.json(user);
});
});
How can put some conditions in mongoose that it return users that contain both "region" && "Sector" in their objects. Currently its only returning the user which have the region keyword in them.
I have tried using $and operator but I couldn't get it to work.
app.get('/user',function(req, res) {
User.find({region: "NA",sector:"Some Sector"}, function(err, user)
{
if (err)
{
res.send(err);
}
console.log(user);
res.json(user);
});
});
If you want data with either region:"NA" or sector:"Some Sector". you can use $or operator.
User.find({$or:[{region: "NA"},{sector:"Some Sector"}]}, function(err, user)
{
if (err)
{
res.send(err);
}
console.log(user);
res.json(user);
});
If you want results that contain any region or sector as long as both are present at the same time you need the following query in your User.find:
{region: {$exists:true},sector: {$exists:true}}
, is the equivalent of $and as long as you are searching different fields.
const dateBetweenDates = await Model.find({
$or: [
{
$and: [
{ From: { $gte: DateFrom } },
{ To: { $lte: DateTo } },
], // and operator body finishes
},
{ _id: req.user.id},
], //Or operator body finishes
})
For anyone else trying to find with multiple conditions using mongoose, here is the code using async/await.
app.get('/user', async (req, res) {
const user = await User.find({region: "NA",sector:"Some Sector"});
if (user) {
// DO YOUR THING
}
});
Related
I'm trying to pull items from my database using each item's id, but am receiving an empty object when running it through Insomnia. For example, in the code below, I would like to pull a category by ID, but also include any associated Products.
Any idea what I might be doing wrong? Thank you in advance!
router.get('/:id', async (req, res) => {
try {
const oneCategory = await Category.findByPk({
include: [{ model: Product }]
});
// console.log(oneCategory);
if (!oneCategory) {
res.status(404).json({ message: 'No category found with that id!' });
return;
}
res.status(200).json(oneCategory);
} catch (error) {
res.status(500).json(error);
}
});
When calling the findByPk method, you need to pass the key you are looking for. In this particular case, the code should look like this:
router.get('/:id', async (req, res) => {
try {
const oneCategory = await Category.findByPk(req.params.id, {
include: [{ model: Product }]
});
if (!oneCategory) {
res.status(404).json({ message: 'No category found with that id!' });
return;
}
res.status(200).json(oneCategory);
} catch (error) {
res.status(500).json(error);
}
});
So just grab the id from the URL with req.params.id and pass it to findByPk. However, it could be a good idea to check so that the id is in fact an integer before doing so :)
I have a use case to search for a particular string on one field and return the results in sorted order based on another field.
The below is the function I'm using in Node.js and the error being thrown.
router.get("/getappts/:username", function (req, res) {
console.log(req.params.username)
collection.find({ username: req.params.username }).sort( {date : 1} ), function (err, appointments) {
if (err) throw err;
console.log(appointments)
res.json(appointments);
}
})
Error - collection.find(...).sort is not a function.
Not sure how to model the query.
But the below query on Mongo Compass seems to work fine -
might be where your callback is, I would suggest using promises instead
router.get("/getappts/:username", async function (req, res) {
try {
console.log(req.params.username)
const appointments = await collection.find({ username: req.params.username }).sort({ date : 1 })
console.log(appointments)
res.json(appointments);
} catch (err) {
throw err;
}
}
I'm building a website with a database using NodeJS, MongoDB, Express, Mongoose etc.
I have two schema set up: Events and a sub-doc schema Categories (among others).
The function pulls in array which contains the data needed to create several categories (this bit works) as well as the Event ID appended to the end.
The first few bits below just grab that ID, then remove it from the array (probably a better way to do this, but again, it works).
As mentioned above, the Categories then create correctly (and even do validation), which is amazing, BUT...
They don't get appended to the Event doc. The doc updates the "categories" field to an applicable number of "null" values, but I cannot for the life of me get it to actually take the IDs of the newly created categories.
I nabbed (and adjusted) the below code from somewhere, so this is where I'm at...
exports.addCategories = catchAsync(async (req, res, next) => {
const categories = req.body;
const length = categories.length;
const eventID = categories[length - 1].eventId;
categories.pop();
Event.findOne({ _id: eventID }, (err, event) => {
if (err) return res.status(400).send(err);
if (!event)
return res.status(400).send(new Error("Could not find that event"));
Category.create(categories, (err, category) => {
if (err) return res.status(400).send(err);
event.categories.push(category._id);
event.save((err) => {
if (err) return res.status(400).send(err);
res.status(200).json(category);
});
});
});
});
Currently the mongoose debug output is showing the following (which confirms that MOST of it is working, but the IDs just aren't being pulled correctly):
> Mongoose: events.updateOne({ _id: ObjectId("614bc221bc067e62e0790875")}, { '$push': { categories: { '$each': [ undefined ] } }, '$inc': { __v: 1 }}, { session: undefined })
Nevermind! I realised that "category" was still an array, rather than an element of the categories array as I'd assumed.
So I replaced that section with this, and now... it works!
Category.create(categories, (err, categories) => {
if (err) return res.status(400).send(err);
categories.forEach((category) => {
event.categories.push(category._id);
});
event.save((err) => {
if (err) return res.status(400).send(err);
});
});
I'm trying to push a value to mongodb when a route is accessed. When i try it pushing through Mongo Shell, the value is pushed, but when i go to the route, nothing is pushed. The route is something like this
router.post('/course/:userid/step-four/:courseid', function(req, res) {
Course.findOne({
"_id": req.params.courseid
}, function(err, course) {
if (err) {
res.send(err);
} else {
User.update({
"_id": ObjectId(req.params.userid)
}, {
$push: {
courseId: req.params.courseid
}
});
Note that i'm able to retrieve both url params when i log them in console, but somehow it is not entering into the db. What can i do?
I want to append a value into my Mongoose array but my array never seems to update. I do the following:
In my controller, I append an eventName into the array eventsAttending like so:
$scope.currentUser.eventsAttending.push(event.eventName);
$http.put('/api/users/' + $scope.currentUser._id, $scope.currentUser)
.success(function(data){
console.log("Success. User " + $scope.currentUser.name);
});
I try to update the array like so:
// Updates an existing event in the DB.
exports.update = function(req, res) {
if(req.body._id) { delete req.body._id; }
User.findById(req.params.id, function (err, user) {
if (err) { return handleError(res, err); }
if(!user) { return res.send(404); }
user.markModified('req.body.eventsAttending');
user.save(function (err) {
if (err) { return handleError(res, err);}
return res.json(200, user);
});
});
};
But my array never seems to update. I've also tried the following:
// Updates an existing event in the DB.
exports.update = function(req, res) {
if(req.body._id) { delete req.body._id; }
User.findById(req.params.id, function (err, user) {
if (err) { return handleError(res, err); }
if(!user) { return res.send(404); }
var updated = _.merge(user, req.body);
updated.markModified('eventsAttending');
updated.save(function (err) {
if (err) { return handleError(res, err);}
return res.json(200, user);
});
});
};
With this approach, my array updates properly, but when I try to perform the http put after one time, I get an error saying Error: { [VersionError: No matching document found.] message: 'No matching document found.', name: 'VersionError' }
Here is my UserSchema:
var UserSchema = new Schema({
name: String,
username: String,
eventsAttending: [{ type: String, ref: 'Event'}],
});
If anyone could help that would be much appreciated.
My guess is the object returning from _.merge is no longer a Mongoose model and some information is getting lost in the transform. I would try manually setting all of the fields coming from the request and use events.attending.push() to add to the array, then saving the updated object and see what happens.
Your first example with markModified looks wrong. Looking at the documentation it should be the name of the field that is modified and it appears that you've put the source location for it.
user.markModified('user.eventsAttending')
However that should not be necessary if you use the push method as Mongoose overrides the built-in array function to track changes.