I got an array by executing the find function in mongoose.
After that, I tried to extract only the values of the data using map.
But only undefined is returned.
I have created an example below. When I run the map function on the frontend and the backend, the results are different.
I don't know why the results are different. Also, is there a way to get the result of number 2 in the backend code?
example mongodb data
{name: 'aaa'},
{name: 'bbb'}
backend code
router.get("/getValue", async (req, res) => {
try {
const result = await Schema.find({}, "-_id");
console.log(result); // original data
let one = result.map((v) => v.name); // 1
res.send({ success: true, result });
} catch (error) {
console.log(error);
res.send({ success: false });
}
});
frontend code
axios.get("/api/getValue").then((res) => {
if (res.data.success) {
const second = res.data.result.map((v) => v.name); //2
}
});
result
// original data
[{name: 'aaa'}, {name: 'bbb'}]
// 1
[undefined, undefined]
// 2
['aaa', 'bbb']
There was a typo in the schema declaration. While editing the schema data, it was confirmed that the name of the key was entered incorrectly.
const Schema = new mongoose.Schema({
username: {
type: String,
}
}
The name of the key in the previous db was name, but in the newly modified schema, only username could be searched, so the variable name could not be found.