I want to populate user in Feed model, and i cant do that, this is what i tried
router.post('/', async (req, res) => {
const newFeed = new Feed(req.body);
try {
const article = await newFeed.populate('created_by');
const finalArticle = await newFeed.save();
res.status(200).json({
success: true,
message: "Successfully created.",
data: finalArticle
})
} catch (err) {
next(err)
}
});
Related
committeeHead is a reference in collection users. I want to populate this id to get the specific data.
tried using Promise.all but I don't completely understand it and it isn't working for me.
const getAllCommittees = async (req, res, next) => {
try {
const committees = await db.collection("committees").get();
const committeesArray = [];
committees.forEach((doc) => {
committeesArray.push({ id: doc.id, ...doc.data() });
});
const committeesWithUsers = await Promise.all(
committeesArray.map((committee) => {
const user = db.collection("users").doc(committee.committeeHead).get();
return {
committee,
user,
};
})
);
res.json(committeesWithUsers);
} catch (err) {
console.log(err);
next(err);
}
};
I want to write a method in node js with mongodb that filters users by
both batch and course
2)only batch if course not enterted
3)only course if batch not enterted
//filter students by either course or batch
export const getUsersByCourseOrBatch = async (req, res) => {
try {
const { course, batch } = req.body
if(course, batch)
{
const users = await UserModel.find({ course: course, batch: batch })
}
else if(course)
{
const users = await UserModel.find({ course: course })
}
else
{
const users = await UserModel.find({ batch: batch })
}
res.status(200).json({
message: `Users from course ${course} and batch ${batch}`,
users,
})
} catch (error) {
res.status(500).json({ message: error.message })
}
}
You can build a custom filter object:
export const getUsersByCourseOrBatch = async (req, res) => {
try {
const { course, batch } = req.body;
const filter = {};
if (course) filter.course = course;
if (batch) filter.batch = batch;
const users = await UserModel.find(filter);
res.status(200).json({
message: `Users from course ${course} and batch ${batch}`,
users,
});
} catch (error) {
res.status(500).json({ message: error.message });
}
};
This is my node JS
const router = require("express").Router();
const Posts = require("../../models/vendorProjectsDatabaseExcellUpload");
router.post('/vendorProjectsDatabasesExcell/save',(req,res) => {
const newPost = req.body;
// console.log(newPost);
// Posts.insertMany(newPost).then((err) =>{
// if(err){
// return res.status(400).json({
// error:err
// });
// }
// return res.status(200).json({
// success:"Project Details Added Successfully"
// });
// });
try {
const options = { ordered: true };
const result = Posts.insertMany(newPost, options).then((err) =>{
if(err){
return res.status(400).json({
error:err
});
}
return res.status(200).json({
success:"Project Details Added Successfully"
});
});
console.log(`All documents were inserted`);
} finally {
console.log('done');
}
});
module.exports = router;
This is my React.js
const uplaodHandler = async (e) => {
// const uplaodHandler = (e) => {
e.preventDefault();
const newPost = items;
// console.log(newPost);
await axios
.post('http://localhost:8072/vendorProjectsDatabasesExcell/save', newPost)
.then((result) => {
alert(result);
alert('New Project Added now');
// navigate('/dashboard/DatabasesUploadProjectFilesVendorProjects', { replace: true });
console.log(newPost);
})
.catch((error) => {
console.log(error);
// console.log(error.response.data);
// console.log(error.response.status);
// console.log(error.response.headers);
});
};
Other post and put request in other pages of the same app is works fine without any error.
In here also the json data array post to the mongo DB without any issue. Only problem is it is giving the bad request 400 error.
Just modify this part:
const result = Posts.insertMany(newPost, options)
.then((res) =>{
return json({success:"Project Details Added Successfully"});
}).catch((err) => {
return json({error:err});
});
I want to delete a doc with id in mongoose. It executes the method but doesn't delete that doc in MongoDB Altas.
Note:Everthing is correct and also Passing id correctly in PostMan.
here is my controller :
const Post = require("../models/Post");
const mongoose = require("mongoose");
exports.postPost = async (req, res) => {
try {
const post = await new Post({
_id: new mongoose.Types.ObjectId(),
title: req.body.title,
desc: req.body.desc,
}).save();
console.log("Saved in db!");
return res.status(201).json({
success: true,
data: post,
});
} catch (error) {
return res.status(500).json({
success: false,
message: "Server Error",
});
}
};
exports.deletePost = async (req, res) => {
let postID = req.params.id;
await Post.deleteOne({ _id: postID }, (err, data) => {
if (err) {
res.status(500).json({
message: "Something went wrong, please try again later.",
});
} else {
res.status(200).json({
message: "Post Deleted",
data: data,
});
}
});
};
here is my posts route:
const express = require("express");
const router = express.Router();
const {
postPost,
deletePost,
} = require("../controllers/posts_controller");
router.route("/:id").delete(deletePost);
router.route("/").post(postPost);
module.exports = router;
here is my postman :
here is my mongodb altas:
use the findOneAndDelete({_id:postId}) instead of deleteOne in posts controller
Or
use findByIdAndDelete(postId) instead of deleteOne in posts controller
exports.deletePost = async (req, res) => {
let postID = req.params.id;
await Post.findByIdAndDelete(postID, (err, data) => {
if (err) {
res.status(500).json({
message: "Something went wrong, please try again later.",
});
} else {
res.status(200).json({
message: "Post Deleted",
data: data,
});
}
});
};
I use the oracle-sage library. And when I want to delete a record, an error occurs.
{
"success": false,
"message": "User.destroy is not a function"
}
How can fix this?
const User = require('../models/User')
const errorHandler = require('../utils/errorHandler')
module.exports.remove = async function (req, res) {
try {
await User.destroy({
USER_ID: req.params.USER_ID
})
res.status(200).json({
message: 'User deleted.'
})
} catch (e) {
errorHandler(res, e)
}
}
Probably .destroy is not a static method, needs an instantiated object. You can try to get the user object first then destroy it.
try {
let user = await User.findOne({ USER_ID: req.params.USER_ID});
user.destroy().then(function(){
res.status(200).json({
message: 'User deleted.'
})
});
} catch (e) {
errorHandler(res, e)
}
Another way to implement destroy method is as below
const deleteUser = async (req,res) => {
console.log('Deleting User by Id')
const userId = await req.params.id
const user = await User.destroy({
where:{
id : userId
},
raw:true
}).catch(error=>console.log(error))