I can't fetch specific data from mongodb atlas
app.post('/profile', (req, res)=>{
let regNo = req.body.regNo;
let mobNo = req.body.mobNo;
let group = regNo.slice(6, 7);
console.log(regNo);
console.log(mobNo);
console.log(group);
if (group = "A") {
candidateGroupA.find({regnumber : regNo, mobnumber : mobNo}, function (err, data) {
console.log(data)
let name = data.name;
console.log(name);
});
}
});
When I used console.log(data), it does work, but console.log(data.name) showing undefined.
These are my mongoose schema and model
const candidateSchema = new mongoose.Schema({
regnumber : String,
group : String,
name : String,
gname : String,
gender : String,
dob: String,
institution : String,
location : String,
mobnumber : Number
});
const candidateGroupA = mongoose.model('candidateGroupA', candidateSchema);
CodePudding user response:
The find
method returns an array, so you can access your data's name with data[0].name
:
app.post('/profile', (req, res)=>{
let regNo = req.body.regNo;
let mobNo = req.body.mobNo;
let group = regNo.slice(6, 7);
console.log(regNo);
console.log(mobNo);
console.log(group);
if (group === "A") {
candidateGroupA.find({regnumber : regNo, mobnumber : mobNo}, function (err, data) {
if (err) {
console.log(err);
return;
}
console.log(data)
if (data.length > 0) {
let name = data[0].name;
console.log(name);
}
});
}
});
You can use findOne
if you need to retrieve a single object:
candidateGroupA.findOne({regnumber : regNo, mobnumber : mobNo}, function (err, data) {
if (err) {
console.log(err);
return;
}
console.log(data)
let name = data.name;
console.log(name);
});