MongoDB with Mongoose API inst returning the data I need the next line is the copy-paste of the property of the data I'm trying to access and returns fine with a find all
"_id": "62657d142ac1ad1cab8ca7f7"
queries tried as first and only argument in both Subscriber.findOne() and Subscriber.findById() include:
{ _id: ObjectId('62657d142ac1ad1cab8ca7f7') }
{ _id: '62657d142ac1ad1cab8ca7f7' }
{
_id: {
$oid: '62657d142ac1ad1cab8ca7f7',
},
}
'62657d142ac1ad1cab8ca7f7'
Using MongoSH i can successfully get the data using this query db.subscribers.findOne({_id: ObjectId("62657d142ac1ad1cab8ca7f7")}) but using it on Mongoose throws a ObjectId not defined error.
function getSubscriber(req, res, next) {
let subscriber;
try {
//ins't working also on runtime only one of these lines is not commented
subscriber = Subscriber.findOne({_id: ObjectId('62657d142ac1ad1cab8ca7f7')});
// also didn't work
subscriber = Subscriber.findById(req.params.id);
if (subscriber == null) {
return res.status(404).json({ message: 'Cannot find subscriber' });
}
} catch (err) {
return res.status(500).json({ message: `error ${err} ${req.params.id}` });
}
res.subscriber = subscriber;
next();
}
Lastly, I know I'm getting to run the middleware as the name property is read after and the query is printed
router.get('/:id', getSubscriber, (req, res) => {
res.send(`Hola ${res.body} ${res.subscriber}`);
});
Output:
Hola undefined Subscriber.findOne({})
I'm trying to get to search with something like .findById(req.params.id) but even using the value directly isn't working.
CodePudding user response:
You are not importing ObjectId from mongoose that's why you are getting error of ObjectId not defined. Where you are using ObjectId('62657d142ac1ad1cab8ca7f7')
You have to use it from mongoose as ObjectId is declared in mongoose module. So need to import mongoose first.
Import mongoose at the top of the file.
const mongoose = require("mongoose");
Then use it to the query.
subscriber = Subscriber.findOne({_id: mongoose.Types.ObjectId('62657d142ac1ad1cab8ca7f7')})
CodePudding user response:
async function getSubscriber(req, res) {
const { id } = req.params;
try {
const subscriber = await Subscriber.findById(id).exec();
if (subscriber == null) {
return res.status(404).json({ message: 'Cannot find subscriber' });
}
res.subscriber = subscriber;
} catch (err) {
return res.status(500).json({ message: `error ${err}` });
}
}