I have two models Connection and Customer. The customer is referenced in Connection. I want to delete the customer from the customer document and remove or update the customer reference from the connection
the customer model is
const mongoose = require('mongoose')
const Customer = mongoose.model('Customer', {
cusName: {
type: String,
required: true,
trim: true
},
nic: {
type: String,
default: false
},
cNumber: {
type: String,
default: true
},
cBranch: {
type: String,
default: true
},
cAddress: {
type: String,
default: true
},
cEmail: {
type: String,
default: true
},
})
module.exports = Customer
and Connection model is
const mongoose = require('mongoose')
const Customer = mongoose.model('Customer', {
cusName: {
type: String,
required: true,
trim: true
},
nic: {
type: String,
default: false
},
cNumber: {
type: String,
default: true
},
cBranch: {
type: String,
default: true
},
cAddress: {
type: String,
default: true
},
cEmail: {
type: String,
default: true
},
})
module.exports = Customer
connection is again referenced by payment model
currunly implemented delete operation as follows.
router.delete('/customer/:id', async (req, res) => {
try {
const customer = await Customer.findByIdAndDelete(req.params.id)
if (!customer) {
return res.status(404).send()
}
res.send(customer)
} catch (e) {
res.status(500).send()
}
})
firstly add a customer Id field in connection
const mongoose = require('mongoose')
const Customer = mongoose.model('Customer', {
...
cusId: {
type: String,
required: true,
},
...
})
module.exports = Customer
and secondly, delete and the customers which have the same cusId
router.delete('/customer/:id', async (req, res) => {
try {
const customer = await Customer.findByIdAndDelete(req.params.id)
const connection = await Connection.deleteMany({ cusId: req.params.id })
if (!customer) {
return res.status(404).send()
}
res.send({ message: "User has been deleted" })
} catch (e) {
res.status(500).send()
}
})
Related
I'm building an API where a user can make a publication to be displayed on a thread. I'm trying to make the author data to be seen with the publication. This way the author data could be get like
console.log( publication.author.completeName )
When saving publication, I save the author field with the value of the user id posting the publication.
Then I'm trying to populate the data like shown here
This is my User model
const dynamoose = require("dynamoose");
const { v4: uuidv4 } = require('uuid');
const userSchema = new dynamoose.Schema(
{
id: {
type: String,
hashKey: true,
default: () => uuidv4(),
},
email: {
type: String,
required: true
},
completeName: {
type: String,
},
pseudo: {
type: String, // Should make check on create and edit to ensure unicity of this column
},
gender: {
type: String,
enum: ['male', 'female', 'other']
},
speciality: {
type: String
},
address: {
type: String,
},
phoneNumber: {
type: String,
}
},
{ timestamps: true }
);
module.exports = dynamoose.model("User", userSchema);
and this is my publication model:
const dynamoose = require("dynamoose");
const { v4: uuidv4 } = require('uuid');
const publicationSchema = new dynamoose.Schema(
{
id: {
type: String,
hashKey: true,
default: () => uuidv4(),
},
photo: {
type: Array,
schema: [String],
default: []
},
description: {
type: String,
required: true
},
anatomies: {
type: Array,
schema: [String],
required: true,
},
specialities: {
type: Array,
schema: [String],
required: true,
},
groupId: {
type: String,
},
author: {
type: String
}
},
{ timestamps: true }
);
module.exports = dynamoose.model("Publication", publicationSchema);
I'm trying to populate the author field when getting all the data like this:
exports.listPublication = async (req, res, next) => {
try {
Publication
.scan()
.exec()
.then( async function (data) {
return Promise.all( data.map(function(pub){
return pub.populate({
path: 'author',
model: 'User'
});
}))
})
.then((data) => {
success(res, { data: data });
})
.catch((err) => {
throw new HttpException(err.message);
});
} catch (err) {
error(next, res, err);
}
}
but the author field is not populated, it only display the value of the author field, which is the string value of the author id.
Help please, I can't figure what I'm doing wrong
This is my Profile Schema:
const mongoose = require('mongoose');
const ProfileSchema = new mongoose.Schema({
user: {
// Special field type because
// it will be associated to different user
type: mongoose.Schema.Types.ObjectId,
ref: 'user',
},
company: {
type: String,
},
website: {
type: String,
},
location: {
type: String,
},
status: {
type: String,
required: true,
},
skills: {
type: [String],
required: true,
},
bio: {
type: String,
},
githubusername: {
type: String,
},
experience: [
{
title: {
type: String,
required: true,
},
company: {
type: String,
required: true,
},
location: {
type: String,
},
from: {
type: Date,
required: true,
},
to: {
type: Date,
},
current: {
type: Boolean,
default: false,
},
description: {
type: String,
},
},
],
education: [
{
school: {
type: String,
required: true,
},
degree: {
type: String,
required: true,
},
fieldofstudy: {
type: String,
required: true,
},
from: {
type: Date,
required: true,
},
to: {
type: Date,
},
current: {
type: Boolean,
default: false,
},
description: {
type: String,
},
},
],
social: {
youtube: {
type: String,
},
twitter: {
type: String,
},
facebook: {
type: String,
},
linkedin: {
type: String,
},
instagram: {
type: String,
},
},
date: {
type: Date,
default: Date.now,
},
});
module.exports = Profile = mongoose.model('profile', ProfileSchema);
This is my view api. It doesn't work. it only return Cast to ObjectId failed for value { 'experience._id': '5edcb6933c0bb75b3c90a263' } at path _id for model profile
router.get('/experience/viewing/:viewexp_id', auth, async (req, res) => {
try {
const exp = await Profile.findById({
'experience._id': req.params.viewexp_id,
});
if (!exp) {
return res.status(404).json({ msg: 'Experience not found' });
}
res.json(exp);
} catch (err) {
console.error(err.message);
res.status(500).send(err.message);
}
});
How can I fix this? I tried looking at the stackoverflow of the same errors. still it doesn't seem to work.
and this is what I am trying to hit
The problem is that you have to convert your string _id to mongoose object id using this function mongoose.Types.ObjectId and my suggestion is to use findOne function instead of findById,
var mongoose = require('mongoose');
router.get('/experience/viewing/:viewexp_id', auth, async (req, res) => {
try {
let id = mongoose.Types.ObjectId(req.params.viewexp_id);
const exp = await Profile.findOne(
{ "experience._id": req.params.viewexp_id },
// This will show your sub record only and exclude parent _id
{ "experience.$": 1, "_id": 0 }
);
if (!exp) {
return res.status(404).json({ msg: 'Experience not found' });
}
res.json(exp);
} catch (err) {
console.error(err.message);
res.status(500).send(err.message);
}
});
var mongoose = require('mongoose');
router.get('/experience/viewing/:viewexp_id', auth, async (req, res) => {
try {
const exp = await Profile.findOne({
'experience._id': mongoose.Types.ObjectId(req.params.viewexp_id),
});
if (!exp) {
return res.status(404).json({ msg: 'Experience not found' });
}
res.json(exp);
} catch (err) {
console.error(err.message);
res.status(500).send(err.message);
}
});
You are saving object id . but your param id is string. convert it in ObjectId. Please check my solution.
router.post(
"/",
[
auth,
[
check("status", "status is required").not().isEmpty(),
check("skills", "skills is required").not().isEmpty(),
],
],
async (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
const {
company,
website,
location,
bio,
status,
githubuername,
skills,
youtube,
facebook,
twitter,
instagram,
linkedin,
} = req.body;
const profileFileds = {};
profileFileds.user = req.user.id;
if (company) profileFileds.company = company;
if (website) profileFileds.website = website;
if (location) profileFileds.location = location;
if (bio) profileFileds.bio = bio;
if (status) profileFileds.status = status;
if (githubuername) profileFileds.githubuername = githubuername;
if (skills) {
profileFileds.skills = skills.split(",").map((skill) => skill.trim());
}
//Build profile object
profileFileds.social = {};
if (youtube) profileFileds.social.youtube = youtube;
if (twitter) profileFileds.social.twitter = twitter;
if (facebook) profileFileds.social.facebook = facebook;
if (linkedin) profileFileds.social.linkedin = linkedin;
if (instagram) profileFileds.social.instagram = instagram;
try {
let profile = await Profile.findOne({ user: req.user.id });
if (profile) {
//update
profile = await Profile.findOneAndUpdate(
{ user: req.user.id },
{ $set: profileFileds },
{ new: true }
);
return res.json(profile);
}
//Create profile
profile = new Profile(profileFileds);
await profile.save();
res.json(profile);
} catch (err) {
console.error(err.message);
res.status(500).send("server Error");
}
}
);
In this application, I am trying to update a field value, if it is successful then I want to save into a log collection, however, not all the data are saved in the log collection, I am not sure if I am doing it the right way, would appreciate if someone could help out.
here is the query :
// both models(Log & Inventory are imported)
router.get("/add_product/:id/:num/:quantity/:order", (req, res) => {
var id = req.params.id;
var quantity = req.params.quantity;
var order = req.params.order;
// console.log('id----', id);
var num_mod = req.params.num;
var modified_count = parseInt(num_mod) - parseInt(quantity);
console.log("num_mod----", num_mod);
Inventory.findByIdAndUpdate(id, { quantity: parseInt(num_mod) }, { new: true }, function(
err,
inventory
) {
if (err) {
console.log("err", err);
res.status(500).send(err);
} else {
console.log(inventory.name);
const newLog = new Log({
name: inventory.name,
description: inventory.description,
price: parseInt(inventory.price),
quantity: parseInt(inventory.quantity),
modified_quantity: parseInt(modified_count),
itemDest: order //this is not being saved
});
newLog.save(function(err, Log) {
if (err) {
console.log(err);
} else {
console.log("add log success");
res.send(inventory);
}
});
}
});
});
URL from front end :
// order is a string
here is the Log schema :
const mongoose = require("mongoose");
const LogSchema = new mongoose.Schema(
{
// _id: mongoose.Schema.Types.ObjectId,
name: { type: String, required: true },
description: { type: String, required: true },
price: { type: Number, required: true },
quantity: { type: Number, required: true },
modified_quantity: { type: Number, required: true },
supplier: String,
taxable: Boolean,
itemDest: String
},
{ timestamps: true }
);
// Create model from the schema
const Log = mongoose.model("Log", LogSchema);
// Export model
module.exports = Log;
and here is the inventory schema
const mongoose = require("mongoose");
//create Schema
const InventorySchema = new mongoose.Schema(
{
// _id: mongoose.Schema.Types.ObjectId,
name: { type: String, required: true },
description: { type: String, required: true },
price: { type: Number, required: true },
quantity: { type: Number, required: true },
supplier: String,
taxable: Boolean
},
{ timestamps: true }
);
// Create model from the schema
const Inventory = mongoose.model("Inventory", InventorySchema);
// Export model
module.exports = Inventory;
My issue is with this line "itemDest: order" in the query, I intend to save the value of "order" extracted from "req.params.order" into "itemDest" but it doesn't save.
I am having an issue with mongoose and nodejs. May be i am writing wrong code or any other problem please help. Here is my controller file. alldata.save gives [ParallelSaveError]
let createData = async function(req,res,next) {
let body = req.body;
let alldata = new League(body);
let start_time = new Date().getTime();
try {
await Leaguecategories.find({})
.then(async function(categories) {
categories.forEach(async function(category) {
//here i am assigning foreign key
alldata.league_category_id = category._id;
await alldata.save(function(err, book){
if(err){
console.log(err);
}else{
res.send({status: 0, statusCode:"success", message: "Successfully inserted."})
}
});
})
})
}
catch (error){
return res.send({status : 1 , statusCode : "error" , message : error.message})
}
}
Here is my Leaguecategories model
var mongoose = require('mongoose');
const league_categories = new mongoose.Schema({
name: {
type: String,
required: true
},
active: {
type: String,
required: true
},
create_date: {
type: Date,
required: true,
default: Date.now
},
league_type_id: {
type: String,
required: 'league_type',
required:true
}
})
module.exports = mongoose.model('Leaguecategories', league_categories)
Here is my League model
var mongoose = require('mongoose');
const league = new mongoose.Schema({
title: {
type: String,
required: true
},
pool_price: {
type: Number,
required: true
},
entry_fee: {
type: Number,
required: true
},
total_spots: {
type: Number,
required: true
},
start_time: {
type: Date,
required: true
},
end_time: {
type: Date,
required: true
},
create_date: {
type: Date,
required: true,
default: Date.now
},
active: {
type: String,
required: true
},
league_category_id: {
type: String,
ref: 'Leaguecategories',
required:true
}
})
module.exports = mongoose.model('League', league)
You have to create new instance of League each time. Like this:
categories.forEach(async function(category) {
//here i am assigning foreign key
let alldata = new League(body);
alldata.league_category_id = category._id;
...
});
Suggestion:
Why are you using both async/await and .then()? You should use only one of them. Also, there are some other problems.
await won't work inside forEach
You are calling res.send() every time you call .save(). This might end up throwing an error as well.
You can refactor the code like this.
try {
const categories = await Leaguecategories.find({});
const promises = categories.map(function (category) {
//here i am assigning foreign key
let alldata = new League(body);
alldata.league_category_id = category._id;
return alldata.save();
});
await Promise.all(promises);
res.send({ status: 0, statusCode: "success", message: "Successfully inserted." })
} catch (error) {
return res.send({ status: 1, statusCode: "error", message: error.message });
}
I want to export two schemas in my model js file and I want use in router js file. I have tried this code below.
This is my certification.js file(models)
const mongoose = require('mongoose');
const Schema = mongoose.schema;
const requestCertificationSchema = mongoose.Schema({
userid: { type: String, require: true },
certName: { type: String, require: true },
certType: { type: String, require: true },
examName: { type: String, require: true },
examYear: { type: String, require: true },
examIndex: { type: String, require: true },
reqDate: {type: String, require: true},
state: { type: String, require: true}
});
const requestCertification = mongoose.model("requestCertification", requestCertificationSchema);
module.exports.saveRequest = function (newRequestCertification, callback) {
newRequestCertification.save(callback);
};
const requestStudentstatusSchema = mongoose.Schema({
studentName: { type: String, require: true },
admissionNum: { type: String, require: true },
dateofAdmission: { type: String, require: true },
currentStatus: { type: String, require: true },
description: { type: String, require: true },
});
const requestStudentstatus= mongoose.model("requestStudentstatus", requestStudentstatusSchema);
module.exports = {
requestCertification: requestCertification,
requestStudentstatus: requestStudentstatus
}
This is my certification.js file(routes)
const router = express.Router();
const Certification = require('../models/certification');
const config = require('../config/database');
router.post("/requestCert", function (req, res) {
const newRequest = new requestCertification({
userid: req.body.userid,
certName: req.body.certName,
certType: req.body.certType,
examName: req.body.examName,
examYear: req.body.examYear,
examIndex: req.body.examIndex,
reqDate:req.body.reqDate,
state: req.body.state
});
console.log(newRequest);
Certification.requestCertification.saveRequest(newRequest, function (err, request) {
if (err) {
res.json({ state: false, msg: "Data inserting Unsuccessfull..!" });
}
if (request) {
res.json({ state: true, msg: "Data inserted Successfully..!" });
}
});
});
When I call this url i have show this error! .
ReferenceError: requestCertification is not defined
Change this code to this one in routes/certification.js
const router = express.Router();
const {requestCertification} = require('../models/certification');
const {requestStudentstatus} = require('../models/certification');
const config = require('../config/database');
router.post("/requestCert", function (req, res) {
const newRequest = new requestCertification({
userid: req.body.userid,
certName: req.body.certName,
certType: req.body.certType,
examName: req.body.examName,
examYear: req.body.examYear,
examIndex: req.body.examIndex,
reqDate:req.body.reqDate,
state: req.body.state
});
// console.log(newRequest);
newRequest
.save()
.then(result => {
console.log(result)
res.json({ state: true, msg: "Data inserted Successfully..!" });
})
.catch(error => {
console.log(error)
res.json({ state: false, msg: "Data inserting Unsuccessfull..!" });
})
});
and delete the saveRequest() function in models/certification.js