Remove referenced ids on mongoose model [duplicate] - node.js

This question already has answers here:
Remove multiple documents from mongo in a single query
(5 answers)
Cascade style delete in Mongoose
(5 answers)
Closed 4 years ago.
The scenario is I have a User model that has an array called filedLeaves which contains ObjectId's that are referenced on another collection. What I want to do is also remove those ObjectIds from its collection once that specific user is removed.
Here's my User Model
var schema = new Schema({
fullName: {
type: String,
required: true,
unique: true
},
leaveCredits: {
type: Number
},
filedLeaves: [{
type: Schema.Types.ObjectId,
ref: 'Leave'
}]
}, {
usePushEach: true
});
And my Leave Model
var schema = new Schema({
userId: {
type: Schema.Types.ObjectId,
ref: 'User'
},
status: {
type: String,
required: true
},
start: {
type: String,
required: true
},
end: {
type: String,
required: true
},
type: {
type: String,
required: true
}
});
I tried this on my User model but it doesn't seem to work.
schema.post('remove', function (user) {
user.filedLeaves.forEach(id => {
Leave.findByIdAndRemove(id)
});
});

Related

How to create a new objectID in mongoose schema?

I want to generate two different objectIds in mongoose schema. One for departureLocation and one for arrivalLocation and want to reference it later.
I imported the object id from mongoose like this
let id = new mongoose.Types.ObjectId()
now I want to generate two different object ids like I said above
const routeSchema = new mongoose.Schema(
{
location: {
departureLocation: {
name: {
ref: "Location",
type: String,
required: true,
},
//want to create new object id here,
subLocation: [String],
_id: {
type: String,
},
},
arrivalLocation: {
name: {
ref: "Location",
type: String,
required: true,
},
//want to create new object id here,
subLocation: [String],
_id: {
type: String,
},
},
},
duration: {
type: Number,
required: true,
},
busId: {
type: mongoose.Schema.Types.ObjectId,
ref: "Bus",
required: true,
},
date: {
type: String,
required: true,
},
},
{
timestamps: true,
}
);
MongoDB will automatically create _id for an object in a schema. You do not need to create one. In this schema, there will be 4 automatically generated _ids one for location, one for departureLocation, one for arrivalLocation, and one for the overall schema.

How can I search through mongoose schema object? [duplicate]

This question already has answers here:
How to query nested objects?
(3 answers)
Closed 3 years ago.
I am trying to search through all the comments and return all comments created by a specific user from my mongodb how ever when i try to search the array returned is empty.
I have tried :
Comment.find({author: {$elemMatch: {username: req.params.username}}}, (err, foundComments) => {
// Code goes here
});
The Mongoose Comment Schema:
const mongoose = require('mongoose');
const commentSchema = new mongoose.Schema({
text: String,
discussion:[{
type: mongoose.Schema.Types.ObjectId,
ref: 'Comment',
}],
createdAt: {
type: Date,
default: Date.now,
},
author: {
id: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User',
},
username: 'String',
avatar: {
image: String,
imageId: String,
},
},
likes: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'User',
}],
dislikes: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'User',
}],
});
module.exports = mongoose.model('Comment', commentSchema);
When I run it I am expecting foundComments to be an array [ array of comments ] but I just get an empty array [].
Comment.find({"author.username":req.params.username});
Comment.find({"username": req.params.username},{"discussion":1,"_id":0})

Mongoose – querying subdocuments referenced by ID

I have 2 schemas connected like this:
const Brand = new mongoose.Schema({
_id: { type: String, required: true },
name: {
type: String,
required: true,
},
products: [{
type: String,
ref: 'Product',
}],
});
const Product = new mongoose.Schema({
_id: { type: String, required: true },
name: {
type: String,
required: true,
},
type: {
type: String,
required: true,
},
});
I want to find brands that have certain types of products, so I wrote a query (not including async/await and promises in the code below for simplicity)
const docs = Brand.find({ 'products.type': 'my-type-here' })
.populate([
{
path: 'products',
},
])
.sort({ index: 1 })
.exec();
This gives me 0 results, yet I know that there are brand with the type of products. What am I doing wrong here? Is it connected with the fact, that products are only referenced by their ids when I invoke find method?

Find all the documents that has same subdocuments mongoose

I have postSchema which references the tagsSchema.
var tagsSchem = new Schema({
name: {
type: String,
required: true
}
}, {
timestamps: true
});
// create a schema
var postsSchema = new Schema({
title: {
type: String,
required: true,
unique: true
},
mainImage: {
type: String
},
category: {
type: String,
required: true
},
body: {
type: String,
required: true
},
postedBy: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
},
tags: [tagsSchem]
}, {
timestamps: true
});
One post can contain any no. of tags. So if a post has 3 tags then I want to get all the posts with those 3 tags without querying it multiple times. Is it possible?
When you perform find, you can use the $in option to find values that are in your array. For example:
posts.find({tags:{$in:{["tag1","tag2","tag3"]}}, function(err,data) {
... //Your code here
}
This will take all the posts that contains one of the three tags. It's important you have to pass an array in the $in option. This should work.

Unique documents using multiple values in Mongoose Schema

I have a special case where our collection needs to make sure each document is unique based on a combination of the email address, and the sweepstakes_id. I've looked all over, but I can't find how to accomplish this type of validation.
Schema definition:
var submissionSchema = new Schema({
client_id: {
type: Schema.Types.ObjectId,
ref: 'Client',
index: true
},
sweepstakes_id: {
type: Schema.Types.ObjectId,
ref: 'Sweepstakes',
index: true
},
email: {
type: String,
index: true
},
data: {
type: Schema.Types.Mixed,
default: []
}
});
You can enforce that using a unique index that includes both fields:
submissionSchema.index({ email: 1, sweepstakes_id: 1 }, { unique: true });

Resources