I am a working on a project for my school. I want to delete employees in the database. This can be done by setting the attribute isDeleted to true.
isDeleted : {
type : Boolean,
default :false,
required : true
}
and the controller function:
const deleteEmployee = async(req, res)=>{
try{
const employeeID = req.body.id;
console.log(employeeID);
const employee = await Member.findByIdAndUpdate(employeeID, {isDeleted : true}, {new : true});
res.status(200).json(employee)
}catch(err){
console.log(err);
}
}
I am not able to update the database. Please suggest changes.
Related
import mongoose from 'mongoose'
const Register_user = mongoose.Schema({
Gender : String,
name : String,
dob : String,
weight : String,
height : String,
userEmail : String,
cart : Array
})
const register_schema = mongoose.model("User_registration" , Register_user)
export default register_schema;
// ^ Add to Cart
export const addToCart = async (req,res) =>
{
try {
// ^ Product Data (actually item data that user added to cart) now need to save this in cart array
const Data = req.body.item;
// ^ to match user Email and cart Data in only and only his cart array
const email = req.body.userEmail;
// ^ finding User based on email
const user = await registerSchema.findOne({userEmail : `${email}`})
if(user)
{
// ^ successfully got the user and his cart
const {cart} = user;
}
} catch (error) {
console.log(`error in adding item to cart + ${error.message}` )
}
}
I want to store item details in cart Array , whatever item user added to cart i want to store it in mongodb cart[] is there a specific method to do this? I tried safe() doesn't work for me
I fixed it by getting an id of a document and using the findByIdAndUpdate method.
if (user) {
// ^ successfully got the user and his cart
const { _id } = user;
console.log(_id);
const { cart } = user;
await registerSchema.findByIdAndUpdate(_id, { cart: [...cart, Data] }).then('done babe');
}
exports.addToCart = async(req,res)=>{
const cart = await schema.cart.findOne({username:req.body.username})
if(cart){
return res.status(404).json({
message:"User's cart is already available, append to the same cart"
})
}
else{
const cart = new schema.cart({
cartId : getValueForNextSequence("item_id"),
username : req.body.username,
productsInCart :req.body.productsInCart
});
console.log(cart.cartId);
await cart.save();
res.status(200).json(cart)
}
}
async function getValueForNextSequence(sequenceOfName){
const sequenceDoc = await schema.counter.findOneAndUpdate(
{"_id": sequenceOfName },
{"$inc":{"sequence_value":1}},
);
return sequenceDoc.sequence_value;
}
THis is the schema for counter I added a document with _id as item_id and sequence_value as 0
const counterSch = new mongoose.Schema({
_id :{
type : String
},
sequence_value:{
type : Number
}
})
getValueForNextSequence method is not returning any value I dont know why please help with this issue.Here I have to increment the cartId automatically but its not happening
I am trying to read from one Mongo collection and then take all that data and save it to a new collection. I am using the same schema, but changing the collection name in two different models :
UserInfo.js :
const mongoose = require('mongoose')
const userSchema = mongoose.Schema({
userID : String,
userName : String
})
let userInfo = mongoose.model('UserInfo', userSchema)
let backUpUserInfo = mongoose.model('BackUpUserInfo', userSchema)
module.exports = {
userInfo : userInfo,
backUpUserInfo : backUpUserInfo
}
I inserted data into the userinfos collection and then I am trying to read that and insert into the backupuserinfos collection :
backup.js :
const UserInfo = require('../Schema/UserInfo').userInfo;
const BackUpUserInfo = require('../Schema/UserInfo').backUpUserInfo;
async function backUp(){
UserInfo.find({}, async function(err1, userInfo){
if (err1) return console.log(err1)
for(let i in userInfo){
try{
let backUpUser = new BackUpUserInfo(userInfo[i])
await backUpUser.save(function (err2, user) {
if (err2) return console.error(err2)
console.log("collection updated")
})
}
catch(err){
console.log(err)
}
}
})
}
I am getting an error that seems to indicate that it is finding a duplicate when trying to save the information, even though the backup collection is empty. This makes me think it is trying to write to the user info collection instead of the back up one. I created the backUp model variable and that is what I run save on, which makes me think it should be specified to run to that collection. Am I doing something wrong here?
Here is the error :
VersionError: No matching document found for id
Easiest way in mongoose would be
UserInfo.aggregate([ { $match: {} }, { $out: "BackupUserInfo" } ])
Else you can use mongodb query OR mongodb copyTo()
db.myoriginal.aggregate([ { $match: {} }, { $out: "mycopy" } ])
//OR
db.source.copyTo("target");
But copyTo() is deprecated since version 3.0.
I want to attach the router.put which will update the Boolean(isOn) in toggle button but firstly I wanted to try how it works and now I am facing the problem.
const express = require("express");
const router = express.Router();
const Buttons = require('../../models/Buttons');
// GET buttons
// This request works perfect
router.get('/', (req,res) => {
Buttons.find()
.sort({name: 1})
.then(buttons => res.json(buttons))
});
// PUT buttons
// This one doesnt work at all
router.put('/:name', function(req,res,next) {
Buttons.findByIdAndUpdate({name: req.params.name},
req.body).then(function(){
Buttons.findOne({name: req.params.name}).then(function(buttons){
res.send(buttons);
});
});
});
module.exports = router;
Model of buttons has only name: String, required: true and isOn: Boolean, required: true and data in db looks like that:
Can you tell me what did I do wrong here?
Code of Buttons modal :
const mongoose = require('mongoose');
const Schema = mongoose.Schema
const buttonSchema = new Schema ({
name: {
type: String,
required: true
},
isOn: {
type: Boolean,
required: true
}
});
module.exports = Buttons = mongoose.model("buttons", buttonSchema);
You ca only use findByIdAndUpdate when you want to update the document by matching the _id of the document
If you want to match the document by any other property (such as name in your case), you can use findOneAndUpdate
Write your query like this
router.put('/:name', function(req,res,next) {
Buttons.findOneAndUpdate({name: req.params.name},
req.body).then(function(){
Buttons.findOne({name: req.params.name}).then(function(buttons){
res.send(buttons);
});
});
});
Hope this helps
Please add your id as well which you have to update in your database
Model.findByIdAndUpdate(id, updateObj, {new: true}, function(err, model) {...
This error occur because findByIdAndUpdate need id of an Object which we want to update so it shows ObjectId error. so pass your id from front end and use it in your back-end to update particulate data.
step 1 : you can create new endpoint for update-name
router.put('/update-name', function(req,res,next) {
//here you can access req.body data comes from front-end
// id = req.body.id and name = req.body.name then use it in your
Buttons.findByIdAndUpdate(id, { name : name }, {new: true}, function(err, model) {...
}
step 2 : try this endpoint /update-name and pass your data in Body from postman
I define nested schema but when I send input data returns nothing,
how can I solve this issue ?
this is my result:
{
"message": "handeling post request to /user-api",
"CreatedUserInfo": {
"_id": "5cbb7fbaad28fe209099a57c"
}
}
this is my code :
const userEduSchema = new mongoose.Schema(
{
eduLevel : String ,
eduField : String,
eduInst :String,
eduCity :String,
eduDate :Date,
proposalTitle :String
}
)
const allEduSchema = new mongoose.Schema(
{
bsc: userEduSchema,
master: userEduSchema,
phd: userEduSchema ,
}
)
module.exports = mongoose.model('Users', allEduSchema )
and it is my user.js for save inpute data in MongoDB I don't know this is true or not:
const userModels = require('../../models/userModels')
router.post('/', (req , res, next) => {
const user = new userModels({
_id : new mongoose.Types.ObjectId,
eduLevel :req.body.eduLevel,
eduField :req.body.eduField,
eduInst :req.body.eduInst,
eduCity :req.body.eduCity,
eduDate :req.body.eduDates,
proposalTitle :req.body.proposalTitle,
})
user.save().then(result =>{
console.log(result)
}).catch (err => {
console.log(err)
})
res.status(201).json ({
message:'handeling post request to /user-api',
CreatedUserInfo : user
})
})```
The problem was in defining the way of get the inputs,I must define the nested object and inside of that put the request bodies as well as I define the nested schema.
bsc:{
bscEduLevel :req.body.bscEduLevel,
bscEduField :req.body.bscEduField,
bscEduInst :req.body.bscEduInst,
bscEduCity :req.body.bscEduCity,
bscEduDate :req.body.bscEduDate,
bscProposalTitle :req.body.bscProposalTitle
}
Have you defined userSchema? If not, you are trying to export a schema which does not exist. Again, in case you have not defined userSchema and you want to export allEduSchema, replace the last line of your model file with this:
const EduSchema = mongoose.model("EduSchema", allEduSchema);
module.exports = EduSchema;
Before you create a new user ,you need to require your "User" moongose Schema. Just like dimitris tseggenes said.
I use async function and try/catch to handle this problem.Maybe you could....
router.post("/", async (request, response) => {
try {
const user = new Users({new user's data here..... });
const result = await user.save();
response.send(result);
} catch (error) {
response.status(400).send(error);
}
});
try catch could avoid some unexpected error and handle it.