Mongoose query between values Express Js - node.js

am playing with MongoDb and Mongoose, and I am trying to filter by price range, for example display properties from 0 to any number (10000),
My model is very simple:
const mongoose = require('mongoose');
const PropertySchema = mongoose.Schema({
title: String,
description: String,
price: Number,
town: String
})
module.exports = mongoose.model('Property', PropertySchema);
And route. this what am up to, set price from 0 to any number, I don’t want to hard-code this max value
const express = require('express');
const router = express.Router();
const Property = require('../models/Property');
router.get('/', async (req, res) => {
try {
const properties = await Property.find({ price: { $in: [ 0, 0 ] } });
res.json(properties);
} catch (err) {
res.json({ message: err });
}
});
URL
properties?price=0&10000
Can anybody help me with this? How can I set range of price for properties?

You need to pass both priceMin & priceMax from queryParams & use same in your query
const express = require('express');
const router = express.Router();
const Property = require('../models/Property');
router.get('/', async (req, res) => {
try {
const properties = await Property.find({ price: { $gte:req.query.priceMin, $lte: req.query.priceMax } });
res.json(properties);
} catch (err) {
res.json({ message: err });
}
});
URL
properties?priceMin=0&priceMax=10000

You can do this using $gt and $lt
properties?min=0&max=10000
router.get('/', async (req, res) => {
let min = req.query.min;
let max = req.query.max;
try {
const properties = await Property.find({ price: { $gt : min , $lt : max } });
res.json(properties);
} catch (err) {
res.json({ message: err });
}
});

Related

API for making query searches not working

I'm trying to fetch all records from MongoDB starting with the Alphabet S but every time I try doing so, it returns nothing but []. I'm using the Params tab on Postman to do this.
The code that I have written is below as well as a snip from Postman to make the question more understandable. I'm pretty sure that the API I have written to perform this has something wrong with it.
The Model file
const mongoose = require('mongoose');
const entry = new mongoose.Schema({
name : {
type : String,
},
collegeName : {
type : String,
},
location : {
type : String,
}
});
const enter = mongoose.model("Student", entry);
module.exports = enter;
index.js
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const mongo = require('mongodb');
const dataModel = require('./model/model');
const MongoClient = mongo.MongoClient;
const uri = "mongodb+srv://coolhack069:XzC6N7dOyUeQl8M9#cluster0.kz6v9.mongodb.net/assignment?retryWrites=true&w=majority";
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
app.use(express.json());
app.use(bodyParser.json());
const port = 3001;
app.get('/api/get', (req, res) => {
client.connect(err => {
if(err) {
throw err;
}
const collection = client.db('assignment').collection('data');
const fetchedData = {};
collection.find(fetchedData).toArray(function(err, result) {
res.send(result);
client.close();
});
})
});
app.get('/api/getStudentDetails', (req, res) => { //The API I have written to query through the Database
client.connect(err => {
if(err) {
throw err;
}
const collection = client.db('assignment').collection('data');
const fetchedData = new dataModel({
name : req.params.name
});
collection.find(fetchedData).toArray(function(err, result) {
res.send(result);
client.close();
})
})
});
app.post('/api/add', (req, res) => { //To add Data
const name = req.body.name;
const collegeName = req.body.collegeName;
const location = req.body.location;
client.connect(err => {
if(err) {
throw err;
}
const collection = client.db('assignment').collection('data');
const storeData = new dataModel({
name : name,
collegeName : collegeName,
location : location
});
console.log(storeData);
collection.insertOne(storeData, function(err, result) {
res.json({
result : "Success"
});
console.log(err);
client.close();
});
})
});
app.listen(port, () => {
console.log(`Application running at http://localhost:${port}`)
})
The Screenshot from Postman
Your find condition is not correct:
const fetchedData = new dataModel({ // ???
name : req.params.name
});
collection.find(fetchedData).toArray(function(err, result) {
res.send(result);
client.close();
})
??? - I guest your meaning is const fetchedData = { name: req.params.name}; - Find every document which have name is req.params.name (S - in your case). But there is no document has name is S in your collection, then it returns [].
If you want to find the documents with S as the first character of their name, you can use Regex syntax:
const query = {
name : new RegExp('^' + req.params.name, 'i'), // i - case insensitive, => /^S/i
};
collection.find(query).toArray(function(err, result) {
res.send(result);
client.close();
})

MongoDB & Mongoose, Save Nested Array of Objects - Node.js

I'm trying to save a nested array of objects to my MongoDB collection but the app is only saving the first object in the nested BankAccountsArray, I've tried using the .markModified() method but haven't got any success. I've attached the data accepted from the frontend part + my model schema + the route, Thanks for the help!
Frontend Data Accepted:
{
companyHoldingPercentage: '10%',
BankAccountsArray: [
{
bankAccountNumber: '32',
bankBranchNumber: '55',
bankName: 'abc'
},
{
bankAccountNumber: '3123',
bankBranchNumber: '412',
bankName: 'cde'
}
]
}
Model:
const mongoose = require("mongoose");
const BankAccountsArraySchema = mongoose.Schema({
bankName: String ,
bankBranchNumber: String ,
bankAccountNumber: String
}
);
const BankAccountsIndexSchema = mongoose.Schema({
companyHoldingPercentage: String ,
BankAccountsArray: [BankAccountsArraySchema]
});
module.exports = mongoose.model(
"bank-accounts-object",
BankAccountsIndexSchema
);
Route:
var express = require("express");
var router = express.Router();
const BankAccountsIndexModel = require("../Models/BankAccountsIndexModel");
router
.route("/BankAccountsIndexRoute")
.get(async (req, res, next) => {
BankAccountsIndexModel.find((err, collection) => {
if (err) {
console.log(err);
} else {
res.json(collection);
}
});
})
.post(async (req, res, next) => {
console.log(req.body);
const {
companyHoldingPercentage,
BankAccountsArray: [{ bankName, bankBranchNumber, bankAccountNumber }],
} = req.body;
try {
const NewBankAccountsIndexModel = new BankAccountsIndexModel({
companyHoldingPercentage,
BankAccountsArray: [{ bankName, bankBranchNumber, bankAccountNumber }],
});
NewBankAccountsIndexModel.markModified(req.body.BankAccountsArray);
NewBankAccountsIndexModel.save();
// res.json(bankAccount);
} catch (err) {
console.error(err.message);
res.status(500).send("Server error");
}
})
module.exports = router;
Can you try to refactor your .post() endpoint like this:
.post(async (req, res, next) => {
try {
let new_bank_account = await BankAccountsIndexModel.create(req.body);
res.status(200).json(new_bank_account);
} catch (err) {
console.error(err.message);
res.status(500).send("Server error");
}
})

Resolving UnhandledPromiseRejectionWarning in express post request

I am trying to make a post request to the server (mongodb) but I get this error:
UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'todo_description' of undefined
I am running mongodb on my localhost
// Require Express
const express = require("express");
// Setting Express Routes
const router = express.Router();
// Set Up Models
const Todo = require("../models/todo");
// Get All Todos
router.get("/", async (req, res) => {
try {
const todo = await Todo.find();
res.json(todo);
} catch (err) {
res.json({ message: err });
}
});
router.get("/:id", async (req, res) => {
try {
const id = req.params.id;
await Todo.findById(id, (err, todo) => {
res.json(todo);
});
} catch (err) {
res.json({ message: err });
}
});
router.post("/add", async (req, res) => {
const todo = new Todo({
todo_description: req.body.todo_description,
todo_responsible: req.body.todo_responsible,
todo_priority: req.body.todo_priority,
todo_completed: req.body.todo_completed,
});
try {
await todo.save();
res.json(todo);
} catch (err) {
res.json({ message: err });
}
});
router.patch("/update/:id", async (req, res) => {
try {
const updateTodo = await Todo.updateOne(
{ _id: req.params.id },
{ $set: { todo_description: req.body.todo_description } }
);
updateTodo.save().then(updateTodo => {
res.json(updateTodo);
});
} catch (err) {
res.json({ message: err });
}
});
router.delete("/delete/:id", async (req, res) => {
try {
const deleteTodo = await Todo.deleteOne({ _id: req.params.id });
res.json(deleteTodo);
} catch (err) {
res.json({ message: err });
}
});
module.exports = router;
my todo model
// Require Mongoose
const mongoose = require("mongoose");
// Define Schema
// const Schema = new mongoose.Schema;
// Define Todo-Schema
const TodoSchema = new mongoose.Schema({
// Creating Fields
todo_description: {
type: String
},
todo_responsible: {
type: String
},
todo_priority: {
type: String
},
todo_completed: {
type: Boolean
},
todo_date: {
type: Date,
default: Date.now
}
});
// Compile Model From Schema
// const TodoModel = mongoose.model("Todos", TodoSchema);
// Export Model
module.exports = mongoose.model("todos", TodoSchema);
error message:
(node:548) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'todo_description' of undefined
at router.post (C:\Users\kinG\Desktop\projects\mountain-of-prototype\mern\backend\routes\todo.js:33:32)
at Layer.handle [as handle_request] (C:\Users\kinG\Desktop\projects\mountain-of-prototype\mern\backend\node_modules\express\lib\router\layer.js:95:5)
thank you
You are accessing todo_description from req.body. req.body will only be available if you add the body-parser middleware or add a similar one yourself.
Add this right before your routes are loaded :
const bodyParser = require('body-parser');
const express = require('express');
const app = express();
app.use(bodyParser.json());
You can also add this to a specific route. Read more about it here.
You should use body-parser in your master file of the application. Which gives you the parsed json before your middle-ware parse the body, which by-default in string. And also make sure you are sending todo_description in the req.body(should check before use).
const bodyParser = require('body-parser');
app.use(bodyParser.json());

Mongoose query doesn't execute properly, no error message

Here's my Schema:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const PostsSchema = new Schema({
userId: String,
postId: String,
title: String,
description: String,
tags: { many: String, where: String, what: String },
date: { type: Date, default: Date.now },
}, { collection : 'posts'});
const Posts = mongoose.model('Post', PostsSchema);
module.exports = Posts;
Here's my route with the query:
const express = require('express');
const router = express.Router();
const mongoose = require('mongoose');
const Posts = require('../models/Posts');
router.get('/', (req, res, next) => {
const refreshOrLoadMore = params.refreshOrLoadMore || '';
if (refreshOrLoadMore === 'loadMore') {
console.log('1');
Posts.find({}).sort({date:-1}).limit(10, (err, data) => {
if(err) {
console.log('2');
res.send(err);
} else {
console.log('3');
res.json(data);
}
});
}
});
The if statement returns true and the first console.log is triggered. But after that none of the other console.logs are triggered and just nothing happens. No data is being send and no error is being send.
So my guess is, that i did something wrong with the Schema, but i did it just as i did my other ones and they do work.
Can someone point out where i went wrong?
Thanks in advance!
Try this
if (refreshOrLoadMore === 'loadMore') {
console.log('1');
Posts.find({}).sort({date:-1}).limit(10)
.exec((err, data) => {
if(err) {
console.log('2');
res.send(err);
} else {
console.log('3');
res.json(data);
}
});
}

Error running mongoose update code ( router.patch() )

I'm getting an error running router.patch() code to update a product on a cloud-based mongoose database. I'm using Postman to simulate the update. Postman's error is showing, "req.body[Symbol.iterator] is not a function." Here is the relevant code:
Products.js:
const express = require('express');
const router = express.Router();
const mongoose = require('mongoose');
const Product = require('../models/product');
router.patch('/:productId', (req, res, next) => {
const id = req.params.productId;
// don't want to update both fields if not needed
const updateOps = {};
// loop through all the operations of the request body
for (const ops of req.body) {
updateOps[ops.propName] = ops.value;
}
Product.update({_id: id}, { $set: updateOps })// $set is a mongoose object
.exec()
.then(result => {
console.log(result);
res.status(200).json(result);
})
.catch(err => {
console.log(err);
res.status(500).json({
error: err
});
});
{req.body.newName, price, req.body.newPrice} ;
res.status(200).json({
message: 'Updated product',
});
});
module.exports = router
Product.js:
const mongoose = require('mongoose');
const productSchema = mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
name: String,
price: Number
});
// export the schema into the Mongoose model
module.exports = mongoose.model('Product', productSchema);
Any help would be greatly appreciated. :-)
As I commented, this part is likely your problem:
for (const ops of req.body) {
updateOps[ops.propName] = ops.value;
}
Since req.body is an Object, I think you want:
for (let [key, value] of Object.entries(req.body)){
updateOps[key.propName] = value;
}
Or something similar.

Resources