Find on Index, return results.
Method:
async index(req,res){
const user = await Usuario.find();
res.json(user);
},
Route:
routes.get('/api/usuarios', Usuario.index);
but findOne({_id}) cannot get results Help pls(i have tryied change params by query, but doesn't works)
method:
async details(req,res){
const { _id } = req.params;
const user = await Usuario.findOne({_id});
res.json(user);
},
route:
routes.get('/api/usuarios.details/', Usuario.details);
First of all you need to change your route
routes.get('/api/usuarios/:_id', Usuario.details);
Then you need to call API like below
http://localhost:<your port number>/api/usuarios/<your id>
Then In your controller
Usuario.findOne(
{ _id: req.params._id }
)
async details(req,res){
const { _id } = req.params;
const user = await Usuario.findOne({_id: _id});
res.json(user);
},
Try the above
Related
I use ORM Sequelize(Postgres). I wrote a code that should return user data by user id, but either it just doesn't return anything, or it says "Support for {where: 'raw query'} has been removed.".
async findOne(req,res) {
try {
const {id} = req.body;
console.log(id);
const user = await User.findOne({where: id})
return res.json({user});
} catch (e) {
console.log(e.message);
}
}
router.post('/getOne', userController.findOne);
You should use an object notation in order to indicate the condition id=:id:
const user = await User.findOne({where: { id: id } })
// OR
const user = await User.findOne({where: { id } })
So Im using mongoose and mongo atlas. I have a single document with a structure as follows:
{_id: ObjectId("3u3ui4t432) ,
name: cat1,
items :
[
{cat1_item1: "something"},
{cat1_item2: "something"}
]}
{_id: ObjectId("3u3uir3bi2) ,
name: cat2,
items :
[
{cat2_item1: "something"},
{cat2_item2: "something"}
]}
currently this endpoint retrieves the entire document, i am just trying to access one category at a time based of a param either url or body
//this gets the specific document i want, but i would prefer to get that document through something like this.
// findOne({ category: req.body.category })
app.post('/targetCategory', async (req, res) => {
const categoryName = req.body.category
categoryCollection.findOne({ _id: "62b9353730ac42a7d390f5ad" }, (err,
data) => {
if (err) {
console.log(err)
} else {
res.send(data)
console.log(categoryName)
}
})
})
const mongoose = require('mongoose')
const Schema = mongoose.Schema;
const categorySchema = Schema({
categories: {
}
})
module.exports = mongoose.model('categoryCollection', categorySchema)
basically I want to use params(?) to only access one category at a time to minimise data sent to the frontend. How do i go about using something like findOne() with the param being either category1 or category2 as I only want the array inside. I am using mongoose, node and express.
model
const mongoose = require('mongoose')
const Schema = mongoose.Schema;
const categorySchema = Schema({
name: String,
// items placeholder, modify if required
items: String[]
})
const Category = mongoose.model('Category', categorySchema)
module.exports = Category
the controller you can use
app.post('/listOne', async (req, res) => {
try {
const categoryData = await Category.findOne({name: req.body.category})
res.send({category: categoryData})
}
catch (e) {
console.log(e)
}
})
another controller solution I suggest
app.get('/category/:name', async (req, res) => {
try {
const categoryData = await Category.findOne({name: req.params.name})
res.send({category: categoryData})
}
catch (e) {
console.log(e)
}
})
To find single data in collection you can use this function or read this in mongoose docs https://mongoosejs.com/docs/api.html#model_Model.findOne
// Find one adventure whose `country` is 'Croatia', otherwise `null`
await Adventure.findOne({ country: 'Croatia' }).exec();
// using callback
Adventure.findOne({ country: 'Croatia' }, function (err, adventure) {});
// select only the adventures name and length
await Adventure.findOne({ country: 'Croatia' }, 'name length').exec();
and to get parameter in express you can use this
app.get('/users/:userId/books/:bookId', (req, res) => {
res.send(req.params)
})
I need to know how to add two database collections in MongoDB. Here is my code
async function run2(){
try {
await client.connect();
const itemCollection2 = client.db('warehouse_inventory').collection('myCollection');
// for my items
app.post('/items', async (req, res)=>{
const newItem = req.body;
const result = await itemCollection2.insertOne(newItem);
res.send(result);
})
}
finally {
}
}
to add or create others database just take a const and change collaction name it will be create database automaticely . to use use that const name to your api cursor
async function run2(){
try {
await client.connect();
const otheritemCollection =
client.db('warehouse_inventory').collection('myCollection2');
// for my other db
app.post('/items', async (req, res)=>{
const newItem = req.body;
const result = await otheritemCollection.insertOne(newItem);
res.send(result);
})
}
finally {
}
}
My code above runs without any errors but the new password isn't saved.
I've been following the bcrypt docs, a blog post and a video and think the three different sources have resulted in my missing something critical.
Any ideas why the new password isn't being saved?
module.exports.submitNewPassword = async (req, res) => {
const slidedHeaderToken = req.headers.referer.slice(-40);
const artist = await Artist.find({ resetPasswordToken: slidedHeaderToken, resetPasswordExpires: { $gt: Date.now() } });
if (!artist) {
console.log("Artist doesn't exist");
} else {
const hashedPassword = async (pw) => {
bcrypt.hash(req.body.password, 12)
}
hashedPassword()
artist.password = hashedPassword;
resetPasswordToken = null;
resetPasswordExpires = null;
console.log("Successfully resubmitted password");
res.redirect('login');
}
}
You should call await artist.save() function after you set some fields
artists is an array of all the artists matching the parameters in the call to .find(). If you just want to find one, use .findOne().
Then after you modify it, use .save() to save it back to the database.
module.exports.submitNewPassword = async (req, res) => {
const slidedHeaderToken = req.headers.referer.slice(-40);
const artist = await Artist.findOne({ resetPasswordToken: slidedHeaderToken, resetPasswordExpires: { $gt: Date.now() } });
if (!artist) {
console.log("Artist doesn't exist");
} else {
const hashedPassword = async (pw) => {
bcrypt.hash(req.body.password, 12)
}
hashedPassword()
artist.password = hashedPassword;
await artist.save();
resetPasswordToken = null;
resetPasswordExpires = null;
console.log("Successfully resubmitted password");
res.redirect('login');
}
}
See the Mongoose tutorial here.
When you make a change to the data using FindOne, you need to save it.
await yourVariable.save()
> I am trying to update a data using updateOne method but i am not able to debug it why it is not working ?
router.post('/edit-category/:slug', async (req,res) =>{
// res.send(req.body.id);
try{
const updatedPost = await Category.updateOne(
{ _id: req.body.id},
{
$set: { title: req.body.title },
$set: { slug: req.body.slug }
}
);
// updatedPost.update((error) => {if(error){console.log("hiiiiiiiii"+error)}});
res.send(updatedPost);
// console.log(updatedPost);
}catch(error){
console.log({message:error})
}
});
Two possibilities:
Check in DB whether the document is there in DB with req.body.id as _id
Try for the below code:
const ObjectId = require('mongodb').ObjectID;
const updatedPost = await Category.updateOne({ _id: ObjectId (req.body.id)}