Delete nested object with mongoose - javascript

I got this mongoose schemas:
const UserSchema = new Schema({
email: {
type: String,
required: true,
unique: true,
},
groups: [
{
groupName: {
type: String,
required: true,
},
groupMembers: [{ type: Schema.Types.ObjectId, ref: "GroupMember" }],
},
],
});
const GroupMemberSchema = new Schema({
firstName: String,
lastName: String,
birthday: Date,
gender: String,
age: Number
});
I want to have 2 routes:
Delete a group member from the groupMembers array based on objectId.
Delete a whole group from the groups array based on objectId.
My attempt for the delete group member route. This route removes the group member from the groupMembers collection succesfully, but the group member still exist in the user collection:
router.delete(
"/:userId/:groupId/:groupMemberId",
catchAsync(async (req, res) => {
const { userId, groupId, groupMemberId } = req.params;
await GroupMember.findByIdAndDelete(groupMemberId);
const user = await User.findById(userId);
const group = user.groups.find((group) => group._id.toString() === groupId);
const groupIndex = user.groups.indexOf(group);
const updatedGroupmembers = user.groups[groupIndex].groupMembers.filter(groupMember=> groupMember._id.toString()!==groupMemberId);
res.send({updatedGroupmembers})
})
);

Did you try using $pull?
router.delete(
'/:userId/:groupId/:groupMemberId',
catchAsync(async (req, res) => {
const { userId, groupId, groupMemberId } = req.params;
await GroupMember.findByIdAndDelete(groupMemberId);
const updatedUser = await User.findByIdAndUpdate({ id: userId }, { $pull: { groups: groupId } }, { new: true });
res.send({ updatedUser });
}),
);

Related

Pull element from array in mongodb

I'm using this schema for the USERS Collection
const usersSchema = new Schema({
username: {
type: String,
required: true,
},
email: {
type: String,
required: true,
unique: true,
},
password: {
type: String,
required: true,
select: false,
},
phone: {
type: Number,
required: true,
},
books: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "books",
},
],
});
and when the user want to delete a book in books collection, it should be delete in the user's books document (The above array) as well.
and I use this query but i get an error
const deleteBook = async (req, res, next) => {
try {
const { id } = req.query;
const deletedProduct = await books.findByIdAndDelete(id).populate(
"author"
);
// IT WORKS AND DELETE THE BOOK IN BOOKS COLLECTION
if (!deletedProduct) {
return next(new ErrorHandler("Product Was Not Found", 404));
}
await Users.findByIdAndUpdate(
deletedProduct.author._id,
{
$pull: { books: deletedProduct._id },
},
(err, docs) => {
// ERROR IS NULL IN HERE
console.log(err);
console.log(docs);
}
);
res.status(200).json("Success");
} catch (err) {
next(new ErrorHandler(err.message, 500));
}
};
Its My query but i get this error.
"Query was already executed: users.findOneAndUpdate({ _id: new ObjectId("THE USER'S ID"
i want to say. The book will be deleted from the books collection, but stay as same in the User's books array.

How to create favorites list with mongodb?

I am creating a blog that will have the home screen where all the recipes will be rendered with a button on each recipe to add to favorites, also the favorites screen where will have all the user's favorite recipes.
So I made my models like this:
const mongoose = require('mongoose');
const { Schema } = mongoose;
const Recipe = mongoose.model(
'Recipe',
new Schema(
{
name: {
type: String,
required: true,
},
ingredients: {
type: String,
required: true,
},
preparation: {
type: String,
required: true,
},
time: {
type: String,
required: true,
},
portion: {
type: String,
required: true,
},
imageName: {
type: String,
required: true
},
imageSize: {
type: Number,
required: true
},
imageKey: {
type: String,
required: true
},
imageUrl: {
type: String,
},
category: Object
},
{ timestamps: true }
)
);
module.exports = Recipe;
const mongoose = require('mongoose');
const { Schema } = mongoose;
const Favorite = mongoose.model(
'Favorite',
new Schema(
{
like: {
type: Boolean,
default: false,
},
recipes: Object,
user: Object,
},
{ timestamps: true }
)
);
module.exports = Favorite;
The bookmark button should change color according to whether like in the bookmark model is true or false but in this case I would not have access to it when I do get for recipes. How can I solve this? In sql I could solve it with relationship but in nosql I don't know how to solve it.
get recipes:
static async getRecipes(req, res) {
const page = req.query.page || 1;
const search = req.query.search || '';
const limit = 10;
const count = await Recipe.find().count();
const totalPages = Math.ceil(count / limit);
if (page > totalPages || page <= 0) {
res.status(400).send({ msg: 'invalid page!' });
return;
}
const recipes = await Recipe.find({
name: { $regex: search, $options: 'i' },
})
.sort('-createdAt')
.limit(limit * 1)
.skip((page - 1) * limit);
res.status(200).json({ recipes: recipes, page, limit, totalPages });
}
get favorites:
static async getAllFavorites(req, res) {
const { page = 1, limit = 10 } = req.query;
// get token
const token = getToken(req);
const user = await getUserByToken(token);
const favorites = await Favorite.find({ 'user._id': user._id })
.sort('-createdAt')
.limit(limit * 1)
.skip((page - 1) * limit);
res.status(200).json({ favorites: favorites, page, limit });
}

Can't pass multiple documents in an array when using findById

I want to find each of the elements in the array by their id and send it with the post request to create a new post. Right now when I create a new post only passes the first index of the array and if I use find() it passes all of the social schemas regardless if it is in the body of the request. I hope this makes sense if it doesn't please let me know. I hope someone can help.
Below is the mongoose schema for the qrcode post also using Joi
const Joi = require("joi");
const mongoose = require("mongoose");
const { themeSchema } = require("./Theme");
const { userSchema } = require("./User");
const { socialSchema } = require("./Social");
const QrCode = mongoose.model(
"QrCode",
new mongoose.Schema({
user: {
type: userSchema,
required: true,
},
name: {
type: String,
maxLength: 255,
required: true,
trim: true,
},
theme: {
type: themeSchema,
required: true,
},
// Social Media Links
social: [
{
type: socialSchema,
required: true,
},
],
})
);
function ValidateQrCode(qrCode) {
const schema = {
userId: Joi.objectId(),
name: Joi.string().max(255).required(),
themeId: Joi.objectId().required(),
socialId: Joi.array().required(),
};
return Joi.validate(qrCode, schema);
}
module.exports.QrCode = QrCode;
module.exports.validate = ValidateQrCode;
this is the post route to create a new qrcode
router.post("/", auth, async (req, res) => {
const { error } = validate(req.body);
if (error) res.status(400).send(error.details[0].message);
const theme = await Theme.findById(req.body.themeId);
if (!theme) return res.status(400).send("Invalid theme.");
const user = await User.findById(req.user._id);
if (!user) return res.status(400).send("Invalid theme.");
const social = await Social.findById(req.body.socialId);
if (!social) return res.status(400).send("Invalid social.");
const qrCode = new QrCode({
user: user,
name: req.body.name,
theme: theme,
social: social,
});
await qrCode.save();
res.send(qrCode);
});
In the body of my Postman request I am inputting the info below
{
"name": "Friends",
"themeId": "60f89e0c659ff827ddcce384",
"socialId": [
"60f89e43659ff827ddcce386",
"60f89e5c659ff827ddcce388"
]
}
To fetch data using ids, you can use below mongodb query simply,
db.collection.find( { _id : { $in : ["1", "2"] } } );
In mongoose,
model.find({
'_id': { $in: [
mongoose.Types.ObjectId('1'),
mongoose.Types.ObjectId('2'),
mongoose.Types.ObjectId('3')
]}
}, function(err, docs){
console.log(docs);
});
Or
await Model.find({ '_id': { $in: ids } });

Building A Referral System Using Nodejs

So am still kinda new to nodejs and am currently on a project and would to integrate a referral sytem into it. Basically on registering a user has a generated unique url that ither users can register with, i have gotten pass this part but now am trying to link the new user and the user who owns the link.
Here are my Models:
Referral Model
import mongoose, { mongo } from 'mongoose';
const referralSchema = new mongoose.Schema({
referralId: [
{
type: String,
unique: true
}
],
referralLink: {
type: String,
unique: true
},
userId: {
type: mongoose.Schema.Types.ObjectId,
ref: 'user'
},
createdAt: {
type: Date,
default: Date.now()
}
})
const Referral = mongoose.model("Referral", referralSchema);
export default Referral;
User Model
import mongoose from 'mongoose';
import passportLocalMongoose from 'passport-local-mongoose'
const userSchema = new mongoose.Schema({
firstName: String,
lastName: String,
email: {
type: String,
trim: true,
required: true,
unique: true,
lowercase: true
},
emailToken: String,
isVerified: Boolean,
username: String,
password: String,
isAdmin: Boolean,
refId: {
type: mongoose.Schema.Types.ObjectId,
ref: "referral",
},
walletId: {
type: mongoose.Schema.Types.ObjectId,
ref: "wallet",
},
plan: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "plan",
}
]
})
userSchema.plugin(passportLocalMongoose);
const User = mongoose.model("User", userSchema);
export default User;
And Here is my code
router.get('/verify-email', async (req, res, next) => {
try {
const user = await User.findOne({ emailToken: req.query.token });
if (!user) {
req.flash('error', 'Token is invalid, Please contact us for assistance');
return res.redirect('/');
}
user.emailToken = null;
user.isVerified = true;
const savedUser = await user.save().then((user) => {
//Create new referral for new user
const newReferrer = new Referral({
referralId: uuidv4(),
referralLink: uuidv4(),
userId: user._id,
});
//save referral to the database
newReferrer.save()
const customUserResponse = { user: savedUser }
customUserResponse.refCode = newReferrer.referralId
req.login(user, async (err) => {
if (err)
return next(err);
req.flash('success', `Welcome to Jenerouszy Mechanism ${user.username}`);
const redirectUrl = req.session.redirectTo || `/dashboard`;
delete req.session.redirectTo;
res.redirect(redirectUrl);
});
});
} catch (error) {
console.log(error);
req.flash('error', 'Something went wrong, please try again or contact us for assistance')
res.redirect('/')
}
});
router.get("/referrals", middlewareObj.isLoggedIn, (req, res) => {
Referral.findOne({ userId: req.user._id })
.populate('user') //Populate model with user
.then(loggedUser => {
//Generate random referral link
const generatedRefLink = `${req.protocol}://${req.headers.host}/register?reflink=${loggedUser.referralLink}/dashboard`
res.render('dashboard/referrals', {
loggedUser: loggedUser,
generatedRefLink: generatedRefLink
})
})
})
I don't know how to go about this, can someone please guide me on what to do.

Mongoose returning empty array

I have a db in Mongo with 2 collections, users and campaigns. For the former, all of my requests (get,post, patch, etc...) work correctly. However, I am having an issue with campaigns.
I can create a new campaign in postman but not 'get' the campaigns. THe request appears successful but returns an empty array.
I have the campaigns split into:
campaignController,
***Model,
***Routes,
and a handlerFactory to cover users and campaigns.
handlerFactory:
exports.getAll = Model =>
catchAsync(async (req, res, next) => {
// To allow for nested GET reviews on tour (hack)
let filter = {};
if (req.params.campaignId) filter = { campaign: req.params.campaignId };
const features = new APIFeatures(Model.find(filter), req.query)
.filter()
.sort()
.limitFields()
.paginate();
// const doc = await features.query.explain();
const doc = await features.query;
// SEND RESPONSE
console.log('-------', doc);
res.status(200).json({
status: 'success',
results: doc.length,
data: {
data: doc
}
});
});
Campaign Model:
const campaignSchema = new mongoose.Schema({
name: {
type: String,
required: [true, 'Campaign name can not be empty!']
},
clientID: {
type: String,
},
creator_id: {
type: String,
},
budget: {
type: Number,
min: 100,
required: [true, 'Campaign name can not be empty!']
},
startStatus: {
type: String,
enum: ['preStart', 'isStarted', 'preEnd'],
default: 'preStart'
},
startDate: {
type: Date,
},
createdAt: {
type: Date,
default: Date.now
},
updatedAt: {type: Date,
default: Date.now
},
isDeleted: {
type: Boolean,
// required: [true, 'Must be true or false!']
default: false
},
Priority: {
type: Boolean,
default: false,
},
location: {
type: String,
enum: ['Helsinki', 'Tallinn'],
default: 'Helsinki'
}
});
campaignSchema.pre('save', function(next) {
if (!this.isModified('createdAt') || this.isNew) return next();
this.updatedAt = Date.now() - 1000;
next();
});
campaignSchema.pre(/^find/, function(next) {
// this points to the current query
this.find({ isDeleted: { $ne: false } });
next();
});
const Campaign = mongoose.model('Campaign', campaignSchema);
module.exports = Campaign;
campaignController:
exports.getAllCampaigns = factory.getAll(Campaign);
exports.getCampaign = factory.getOne(Campaign);
exports.createCampaign = factory.createOne(Campaign);
exports.updateCampaign = factory.updateOne(Campaign);
exports.deleteCampaign = factory.deleteOne(Campaign);
exports.getMe = (req, res, next) => {
req.params.id = req.campaign.id;
next();
};
exports.deleteCurrentCampaign = catchAsync(async (req, res, next) => {
await User.findByIdAndUpdate(req.campaign.id, { active: false });
res.status(204).json({
status: 'success',
data: null
});
});
campaignRoutes:
const router = express.Router();
router
.route('/')
.get(campaignController.getAllCampaigns)
.post(
authController.protect,
authController.restrictTo('admin', 'super-admin'),
campaignController.createCampaign
);
router
.route('/:id')
.get(campaignController.getCampaign)
.patch(
authController.protect,
authController.restrictTo('admin', 'super-admin'),
campaignController.updateCampaign
)
.delete(
authController.protect,
authController.restrictTo('admin', 'super-admin'),
campaignController.deleteCampaign
);
module.exports = router;
Any idea where I am going wrong?
All code looks good but may be problem is,your collection not contain any records whose isDeleted=true.
because "find query middleware" in campaignModel is called before any find* query and it find all document whose isDeleted != false.

Categories

Resources