I want to exclude default _id or any one of the two fields (time and count) while fetching the data result from JSON API in my node-express app. I tried several ways to do so but still the data shows the field that I marked as excluded in GET response. In my code below, I used _Id as sample, but similar problem persists for every field of my database. Here are some of the ways I figured out that didn't worked:
exports.get_all_clothing = (req, res, next) => {
Clothing.find({}, {projection:{_id: 0}})
.exec()
.then(docs => {
console.log(docs);
res.status(200).json(docs);
})
.catch(err => {
console.log(err);
res.status(500).json({
error: err
});
});
}
AND
exports.get_all_clothing = (req, res, next) => {
Clothing
.find({}).project({ _id: 0 })
.exec()
.then(docs => {
console.log(docs);
res.status(200).json(docs);
})
.catch(err => {
console.log(err);
res.status(500).json({
error: err
});
});
}
AND
exports.get_all_clothing = (req, res, next) => {
Clothing.find('-_id')
.exec()
.then(docs => {
console.log(docs);
res.status(200).json(docs);
})
.catch(err => {
console.log(err);
res.status(500).json({
error: err
});
});
}
Everytime I keep getting the result as
[ { _id: 5cb73
time: '656
count: 43,
__v: 0 },
{ _id: 5cb73
time: '155
count: 60,
__v: 0 },
{ _id: 5cb73
time: '155
count: 56,
__v: 0 }, ....]
Please help out.
Try this:
exports.get_all_tweets = (req, res, next) => {
Clothing.find({}, {_id: 0})
.exec()
.then(docs => {
console.log(docs);
res.status(200).json(docs);
})
.catch(err => {
console.log(err);
res.status(500).json({
error: err
});
});
}
You can use query.select to get your desired results.
exports.get_all_tweets = (req, res, next) => {
Clothing.find()
.select('-_id')
.then(docs => {
console.log(docs);
res.status(200).json(docs);
})
.catch(err => {
console.log(err);
res.status(500).json({
error: err
});
});
}
Related
Im in a specific situation where I have to select all records in a mongo db collection but also a record with a specific Id. I understand how to get the whole lot of records but how can I query a record with a specific id as well.
app.get('/:id', (req, res) => {
Term.find().sort({ "term": 1 })
.then(result => {
res.render('about', { title: 'About page', terms: result });
})
.catch(err => {
console.log(err);
});
const id = req.params.id;
Term.findById(id)
.then(results => {
res.render('about', { specific: results })
})
});
would the above code work as I have queried the whole database with Term.find but also Term.findbyId(id)
I think this is what you need, return both things in the same handler.
app.get("/:id", (req, res) => {
const id = req.params.id;
Term.find()
.sort({ term: 1 })
.then(result =>
Term.findById(id).then(results =>
res.render("about", {
specific: results,
title: "About page",
terms: result
})
)
)
.catch(err => console.log(err));
});
If you select all records in first query and load all data from db - you don't need a second query. You can do this with plain javascript with data that already received from first query.
app.get('/:id', (req, res) => {
Term.find().sort({ "term": 1 })
.then(result => {
const specific = result.find(item => item._id.toString() === req.params.id);
res.render('about', {
specific,
title: 'About page',
terms: result
});
})
.catch(err => {
console.log(err);
});
});
If you don't load all data. Probably you have some paginations. You can run 2 query concurrently.
app.get('/:id', (req, res) => {
Promise.all([
Term.find().sort({ "term": 1 }),
Term.findById(req.params.id)
])
.then(values => {
res.render("about", {
title: "About page",
terms: values[0],
specific: values[1]
})
})
.catch(error => console.log(err));
});
product-operations.component.ts
deleteProduct() {
this.productsService.delete_product(this.deleteID).subscribe((res: any) => {
console.log("helloooooo");
});
};
product.service.ts
delete_product(id) {
return this.http.delete("http://localhost:3000/delete_product/" + id);
}
backend
exports.deleteProduct = (req, res, next) => {
const id = req.param("id");
Product.deleteOne({ _id: id })
.then(() => {
console.log("deleted");
})
.catch(err => {
console.log(err);
});
};
Problem:
In the above codes, the deleteProduct function in product-operations.component.ts doesn't work properly. More precisely, it does the removal. But after doing the uninstall, subscribe doesn't run its contents. This prevents my instant update after deletion. How can I solve this?
Try to send a response back from the server.
exports.deleteProduct = (req, res, next) => {
const id = req.param("id");
Product.deleteOne({ _id: id })
.then(() => {
res.send({}) // or res.send({id: id})
console.log("deleted");
})
.catch(err => {
res.status(500)
res.send({error: err})
console.log(err);
});
};
I have created three collections,
family {familyname , _id}
root {rootname familyId _id}
child{childname rootId familyId _id}
Now if I delete family, root, and child should also be deleted
So far, I have tried this but it's not working
router.delete("/:familyId", (req, res, next) => {
const id = req.params.familyId;
Family.remove({ _id: id })
Root.remove({ _id: id })
Child.remove({ _id: id })
.exec()
.then(result => {
res.status(200).json({
message: 'deleted',
});
})
.catch(err => {
console.log(err);
res.status(500).json({
error: err
});
});
});
You can use the promises returned by the .remove() method as follows:
router.delete("/:familyId", (req, res, next) => {
const id = req.params.familyId;
const family = Family.remove({ _id: id });
const root = Root.remove({ familyId: id });
const child = Child.remove({ familyId: id });
Promise.all([family, root, child]).then(result => {
console.log(result);
res.status(200).json({
message: 'deleted',
});
}).catch(err => {
console.error(err);
res.status(500).json({
error: err
});
});
});
I'm stuck I'd like to get all the ratings for a fablab and can't get the code to be asynchronous.
So here I get an empty array since the code is not async.
This is my example :
// get all ratings for a fablab
rating_router.get('/get/:id', (req, res) => {
Fablab.findById({_id:req.params.id}, (err, fablab) => {
if(err) send(err)
else {
let ratingstest = []
fablab.rating.map(ratingID => {
Rating.findById({_id:ratingID}, (err, rating) => {
if(err) send(err)
else ratingstest.push(rating)
})
})
return ratingstest
}
})
})
You could add a conditional to check when the last query resolves and then pass the array of results to res.send:
rating_router.get('/get/:id', (req, res) => {
Fablab.findById({ _id: req.params.id }, (err, fablab) => {
if (err) {
res.send(err)
}
else {
let ratingstest = []
fablab.rating.forEach(ratingID => {
Rating.findById({ _id: ratingID }, (err, rating) => {
if (err) {
res.send(err)
}
else {
ratingstest.push(rating)
// Check if this is the last one
if (ratingstest.length == fablab.rating.length) {
res.send(ratingstest)
}
}
})
})
}
})
})
However, it might be nicer to use promises:
rating_router.get('/get/:id', (req, res) => {
Fablab
.findById({ _id: req.params.id })
.then(fablab => fablab.rating || [])
.then(ratingIDs => ratingIDs.map(ratingID =>
Rating.findById({ _id: ratingID })
))
.then(ratingArr => Promise.all(ratingArr))
.then(result => res.send(result))
.catch(err => res.send(err))
})
I hope this helps.
Inside mapping function, make findById promise
function findByIdPromise(){
return new Promise((resolve,reject)=>{
Rating.findById({_id:ratingID}, (err, rating) => {
if(err) reject(err)
else {
ratingstest.push(rating)
resolve()
}
})
})
}
After mapping is done, you'll have array of promises, then just do
Promise.all(fablab.rating).then(()=>console.log(ratingstest))
Hi friends I'm trying to find in my subDoc category string matching
Here is the code:
router.get('/:_categoryName', (req, res, next) => {
Malgezot.findOne({ 'items.category': req.params._categoryName }, (err, malgezot) => {
if(err) return res.render('body/category', {info: ''});
console.log(malgezot);
});
});
But the results is all of the items!
I also tried:
router.get('/:_categoryName', (req, res, next) => {
Malgezot.find({'items': { 'category': req.params.categoryName }}, (err, malgezot) => {
if(err) return res.render('body/category', {info: ''});
console.log(malgezot);
});
});
If your data is in form of object then query should be :
router.get('/:_categoryName', (req, res) => {
const { _categoryName } = req.params;
Malgezot.findOne({
'items.category': _categoryName
}).then((data) => {
if (data) {
res.status(200).json(data)
}
}).catch((err) => {
res.status(500).json({
message: 'Internal server error'
});
});
});
Or if your data in form of array then your query should be:
router.get('/:_categoryName', (req, res) => {
const { _categoryName } = req.params;
Malgezot.findOne({
item : { $in : [{ category: _categoryName }] }
}).then((data) => {
if (data) {
res.status(200).json(data)
}
}).catch((err) => {
res.status(500).json({
message: 'Internal server error'
});
});
});