I'm learning MongoDB and Node.js. While I'm trying to making small database, I encountered a problem. The result of data is shown as array, not object.
What I want to do : show the result of data as object.
Data: [{"_id":"59e06e1dbbeee5a09e8fb46b","id":"123","name":"Dog chew toy","price":10.99},{"_id":"59e06e1dbbeee5a09e8fb46c","id":"456","name":"Dog pillow","price":25.99}]
When I type localhost:3000/findToy?id=123, the following data is shown.
[{"_id":"59e06e1dbbeee5a09e8fb46b","id":"123","name":"Dog chew toy","price":10.99}]
The data is array. But I want to show it as object like the below.
{"_id":"59e06e1dbbeee5a09e8fb46b","id":"123","name":"Dog chew toy","price":10.99}
How can I accomplish this?
index.js
var express = require('express');
var app = express();
app.set('view engine', 'ejs');
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true}));
app.use(bodyParser.json());
var Animal = require('./Animal.js');
var Toy = require('./Toy.js');
var router = express.Router();
app.get('/findToy?:id', (req, res) => {
var query = {};
if(req.query.id) {
query.id = {$regex: req.query.id };
}
if(Object.keys(query).length == 0){
res.json({});
}
Toy.find(req.query.id,(err, toys) => {
if(err) {
res.type('html').status(500);
res.send('Error:' + err);
}
else {
res.json(toys);
console.log(toys)
}
})
});
app.listen(3000, () => {
console.log('Listening on port 3000');
});
module.exports = app;