i'm trying populate method in mongoose.
this is my query
await User.findOne({_id: req.params.userId}).populate({ path: 'review' }).then(result=>{
console.log("here" + result)
if(result && result.length != 0){
return res.json({
msg: "all reviews retrieved",
data: result
})
}
else {
return res.json({
msg: "no review found"
})
}
})
and this is the result i'm getting
enter image description here
now i want to get userSender data. anyone who can help me how to populate user data using reviewSender id?
Try this:
User.findOne({_id: req.params.userId}).populate('review').populate('review.reviewSender');
Related
I'm diving into NoSql injection so I'm trying to hack my db with postman to see if there is any vulnerability. My requests use parameters to query fields as:
User.find({
// name: req.params.name
name: req.query.name
},
function (err, result) {
if (err) {
console.log('Mongoose findUsers name error: ', err);
res.status(505).send({ error: "Internal error." });
return;
}
if (result != null) {
console.log("Mongoose findUsers name: ", result);
res.status(200).send({
message: "Found users :",
data: result
});
} else {
console.log("Mongoose findUsers name: No user found");
res.status(404).send({
message: "No user found."
});
}
});
So I'm trying to pass a name parameter as {"$ne": null} or {"$gt": ""} , so the query will be localhost:5000/api/users?name={"$ne": null}. Though the response I get from the findOne method is not null, it will return an empty array. Does than mean that I'm already protected against NoSql injections and not need to sanitize queries parameters or am I just not using the right value to perform an injection? What other test could I run to try and check properly if nosql injection are possible ?
As always many thanks for your help.
Cheers.
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);
}
I have this function on my backend:
exports.updatePacienteByCodigo = function (req, res) {
let codPaciente = req.params.codPaciente;
let params = req.body; // This is the data what come from frontend = {'testRealizados':['example'], 'respuestas':['example'], 'codMedico':'example'}
Paciente.findOneAndUpdate({ codPaciente: codPaciente }, {
'$push': {
'testsRealizados': params.testsRealizados,
'respuestas': params.respuestas,
'codMedico': {'$ne':params.codMedico} //here is the problem
}
}).then(
pacienteEncontrado => {
if (!pacienteEncontrado) {
res.status(404).send({ accion: 'updatePaciente', mensaje: 'Ese paciente no existe' });
} else {
res.status(200).send({ accion: 'updatePaciente', mensaje: 'Paciente actualizado correctamente' });
}
}
).catch(err => { res.status(500).send({ accion: 'updatePaciente', mensaje: 'Error ' + err }) })
};
This query throw me this error "Error CastError: Cast to [string] failed for value \"[{\"$ne\":\"o8qjdeli\"}]\" at path \"codMedico\""}
What I want to do is, if codMedico have the same value in the database than the param codMedico dont update that field.
I tried that but that didnt work. I am out of ideas so here I am. Thanks.
[SOLVED]
I tried with $addToSet method and it works perfectly like #Plancke told me in the comments.
I tried with $addToSet method and it works perfectly like #Plancke told me in the comments.
I'm the beginner of nodejs and MongoDB.I tried to design RESTAPI but there was a problem.
Here is my router code.
app.post('/fcm',function(req,res){
var beaconid = req.body.beacon_id;
var my_token_id = req.body.user_id;
User.find({beacon_id: beaconid}, function(err, output){
if(err) return res.status(500).json({error: err});
if(!output) return res.status(404).json({error: 'user not found in User collections.'});
console.log("output user id :"+output.user_id + " beacon: " +output.beacon_id );
target_token_id = output.user_id;
res.json(output);
});
});
And this is user schema.
var userSchema = new Schema({
user_id: String,
beacon_id: String
});
The result of above function in the console is:
output user id: undefined , beacon: undefined.
But json from res function is printed properly.
This codes look like very simple but I don't know what is the problem.
Please somebody help me.
By using find, you are expecting 1 document or more. This means that the method <Model>.find() should logically return an array. You can make sure that is what happens by logging the output just after the query to make sure it is an array of documents.
To solve your problem, you can either access the document at index 0 of the array:
User.find({beacon_id: beaconid}, function(err, output){
if(err) return res.status(500).json({error: err});
if(!output) return res.status(404).json({error: 'user not found in User collections.'});
console.log("output user id :"+output[0].user_id + " beacon: " +output[0].beacon_id );
target_token_id = output[0].user_id;
res.json(output);
});
Or use findOne() instead, that returns only one document.
User.findOne({beacon_id: beaconid}, function(err, output){
if(err) return res.status(500).json({error: err});
if(!output) return res.status(404).json({error: 'user not found in User collections.'});
console.log("output user id :"+output.user_id + " beacon: " +output.beacon_id );
target_token_id = output.user_id;
res.json(output);
});
My Database having this value
id: ObjectId(6a00683bac41ce1054774e7d),
currentuserid: "69fc06dbf88c8c15042b4e36",
dataset: Array
0: Object
userid: "69fc06dbf88c8c15042b4e37"
1: Object
userid: "69fc06dbf88c8c15042b4e38"
2: Object
userid: "69fc06dbf88c8c15042b4e39"
Now I want to make query which first Check That "currentuserid" is Exist under array. if Value exist then returns true else false. I am new in mongodb. I also read $in Operator . My query is
Mydata.find({ dataset: { $in: [{userid: '69fc06dbf88c8c15042b4e36'}] } }, function(req, res){
if(err){ console.log('Not Matched'); }
else{ console.log('Matched') }
});
But i am unable to achieve it
Try this:
Mydata.findOne({dataset:{$elemMatch:{userid:'69fc06dbf88c8c15042b4e37'}}},function(err, data){
if(err){
throw err;
} else if(data){
console.log('Matched');
}else{
console.log('Not Matched')
}
});
It will result data as null for userid 69fc06dbf88c8c15042b4e36.