How do you set select=false for a nested Mongoose document? - javascript

This is my User schema:
var userSchema = mongoose.Schema({
profile: {
username: { type: String, required: true, unique: true },
role: String
},
auth: {
hashedPassword: { type: String, required: true },
facebookToken: String,
twitterToken: String,
googleToken: String
},
});
I want to set select = false for the whole auth object. How would I do that?

Simply add it this way:
var userSchema = mongoose.Schema({
profile: {
username: { type: String, required: true, unique: true },
role: String
},
auth: {
type : {
hashedPassword: { type: String, required: true },
facebookToken: String,
twitterToken: String,
googleToken: String
},
select: false //<---- added here
}
});

Related

How to get following users posts from mongodb

hi I'm using React with mongoDB I'm new to the mongoDB. I guess My schemas is having problems
how do I get posts that I'm following users. I've been facing this problem for a week
I can get All the posts of my following users, I think it might be unnecessary I'd like to just get lastest 10 posts of my following users
if there is a tip to get posts please let me know thanks for reading this question
Here's my Post Schema
import mongoose from "mongoose";
const postSchema = mongoose.Schema({
title: String,
message: String,
name: String,
tags: [String],
picture: String,
likes: {
type: [String],
default: [],
},
createdAt: {
type: Date,
default: new Date(),
},
profilePicture: String,
userId: String,
comments: {
type: [
{
commentUserId: String,
commentUserName: String,
comment: String,
createdAt: Date,
},
],
},
});
const Post = mongoose.model("Post", postSchema);
export default Post;
Here's User Schema
import mongoose from "mongoose";
import bcrypt from "bcrypt";
const userSchema = mongoose.Schema({
name: { type: String, required: true },
email: { type: String, required: true, unique: true },
password: { type: String, required: true },
id: { type: String },
profilePicture: {
type: String,
default:
"https://icon-library.com/images/anonymous-avatar-icon/anonymous-avatar-icon-25.jpg",
},
isAdmin: {
type: Boolean,
required: true,
default: false,
},
userPosts: [
{
_id: String,
title: String,
picture: String,
message: String,
tags: [String],
name: String,
profilePicture: String,
userId: String,
likes: [String],
comments: [
{
commentUserId: String,
commentUserName: String,
comment: String,
createdAt: Date,
},
],
},
],
following: {
type: [String],
default: [],
},
followers: {
type: [String],
default: [],
},
notifications: [
{
_id: mongoose.Schema.Types.ObjectId,
sender: String,
notificationType: String,
read: Boolean,
},
],
});
const User = mongoose.model("User", userSchema);
export default User;

How to get only matched data in mongoose (node.js)?

I am building a bus ticket booking app in node.js. I want to fetch only related data about queries not all the data But I am getting all the data about Bus.
Here is the location model. only admin can enter data about locations.
const locationSchema = new mongoose.Schema(
{
departureLocation: {
name: {
type: String,
required: true,
lowercase: true
},
time: {
type: String,
required: true,
},
subLocations: { type: [String], lowercase: true },
},
arrivalLocation: {
name: {
type: String,
required: true,
lowercase: true
},
time: {
type: String,
required: true,
},
subLocations: { type: [String], lowercase: true },
},
},
{
timestamps: true,
}
);
Here is the route table. Again admin...
const routeSchema = new mongoose.Schema({
location:{
type: mongoose.Schema.Types.ObjectId,
ref: 'Location',
required: true
},
duration: {
type: Number,
required: true
},
date: {
type:String,
required: true
},
},
{
timestamps: true,
});
Bus model: Admin...
const busSchema = new mongoose.Schema({
busNumber: {
type: String,
unique: true,
required: true,
},
seats: {
type: Number,
},
route: {
type: mongoose.Schema.Types.ObjectId,
ref: "Route",
required: true,
},
},
{
timestamps: true,
});
and here finally the booking table:
const bookingSchema = new mongoose.Schema({
userId: {
type: mongoose.Schema.Types.ObjectId,
ref: "User",
required: true,
},
busId: {
type: mongoose.Schema.Types.ObjectId,
ref: "Bus",
required: true,
},
passengers: [
{
name: { type: String, required: true, trim: true },
gender: { type: String, required: true, trim: true },
age: { type: Number, required: true, trim: true },
}],
phone: {
type: Number,
required: true,
},
email: {
type: String,
required: true,
},
bookingDate: {
type: String,
required: true,
},
fare: {
type: Number,
required: true,
},
seats: {
required: true,
type: [Number],
},
departureDetails: [
{
city: { type: String, required: true, trim: true },
location: { type: String, required: true, trim: true },
time: { type: String, required: true, trim: true },
date: { type: String, required: true, trim: true },
},
],
arrivalDetails: [
{
city: { type: String, required: true, trim: true },
location: { type: String, required: true, trim: true },
time: { type: String, required: true, trim: true },
date: { type: String, required: true, trim: true },
},
],
},{
timestamps:true
});
Whenever an authorized user enters the booking data It is getting saved to the database. No problem whatsoever
Now I want to show every user(Non-authorized as well) of my app about trips(routes), the bus which will run on that particular trip and reserved and available seats in that particular bus which is currently stored.
But the problem is that I am getting all the buses even if it is not on that trip.
here is the query:
router.get("/trip/single", async (req, res) => {
if (!req.query.departure || !req.query.arrival || !req.query.date) {
return res.send({
error: "Please enter the data to get the trip",
});
}
const { departure, arrival, date } = req.query;
let locations = await Location.find({
'departureLocation.name': departure,
'arrivalLocation.name': arrival,
});
const ids = locations.map(location => location._id)
const routes = await Route.find({$and: [{location : {$in: ids}},{date}]});
const route = routes.find(()=>{
return ([{ date }, { routes }])
});
let buses = await Bus.find({})
let matchedBuses = buses.filter((bus)=> {
return bus.routes === locations._id
})
const bookings = await Booking.find({})
const busIdWithSeatsObj = {}
for(let i = 0; i < matchedBuses.length; i++){
let currentBusSeats = []
const busBookings = bookings.filter((booking) => {
return (booking.departureDetails.date === date &&
booking.busId.toString() === matchedBuses[i]._id.toString()
)
})
busBookings.forEach((booking) => {
currentBusSeats = [...currentBusSeats, ...booking.seats]
})
busIdWithSeatsObj[matchedBuses[i].seats] = currentBusSeats
}
res.status(200).send({route, matchedBuses, busIdWithSeatsObj});
});
Now I also want to fetch details by Id(only single bus).
How to do that?
Can anyone help me out here?
here's the input data image with result for date: 2022-06-02 which is actually available in the database : https://i.stack.imgur.com/FlfaG.png
This is the second query with result for date: 2022-06-01. It is not available in the database still showing matchedBus.: https://i.stack.imgur.com/xY5pW.png Now route data is gone but matched buses still shows.

i want to check if current user is following other user

i want to check if current user is following other use lets say check if user A is following user B.
User Model:-
const UserSchema = new Schema({
email: {
required: true,
type: String,
unique: true,
lowercase: true,
validate: (value) => {
if (!validator.isEmail(value)) {
throw new Error('Invalid email address.');
}
}
},
fullName: {
required: true,
type: String,
},
username: {
required: true,
type: String,
unique: true,
lowercase: true,
minlength: 3,
},
password: {
type: String,
minlength: 8,
},
avatar: String,
bio: {
type: String,
default: null,
maxlength:300,
},
location: {
type: String,
default: 'Bangalore'
},
website: {
type: String,
default: null,
},
joindate: {
type: Date,
default: new Date()
},
isVerified:{
type:Boolean,
default:false,
}
})
const UserModel = mongoose.model('User', UserSchema);
module.exports = UserModel;
Followings Model:-
const FollowingsSchema = new Schema({
user: {
ref: 'User',
unique:true,
type: Schema.Types.ObjectId,
},
followings: [{
user: {
type: Schema.Types.ObjectId,
ref: 'User'
}
}]
})
const Followings = mongoose.model('Followings', FollowingsSchema);
module.exports = Followings;
Followers Model:-
const FollowersSchema = new Schema({
user: {
ref: 'User',
unique:true,
type: Schema.Types.ObjectId,
},
followers: [{
user: {
type: Schema.Types.ObjectId,
ref: 'User'
}
}]
})
const Followers = mongoose.model('Followers', FollowersSchema);
module.exports = Followers;
currently i was able to achieve this by iterating through each follower and check if user exist in that user followers list.
i want to achieve this with mongodb aggregation ,im new to mongob

Mongoose querying an array of objects

How to querying an array using Mongoose ?
search Schema:
const searchschema = new schema({
yeardate: { type: Number, required: true, min: 1820 },
word: { type: String, required: true, index: true },
user: [{ type: schema.Types.ObjectId, ref: 'User' }] })
user Schema:
const userschema = new schema({
username: { type: String, required: true, unique: true, index: true },//
name: { type: String, default: 'NoName' },
gender: { type: String, default: 'male' }, })
This is the query I have tried but did not work:
searchmodel.paginate({ 'user': { $elemMatch: { gender: 'female' } } }, { page: page, limit: 5, populate: ['user'] }).then(searches => {
if (!searches) {
return res.json({ message: 'there is no search' })
}else {
return res.json(searches)
}
})

findByIdAndUpdate keeps being caught in .catch

So when I am executing my findByIdAndUpdate it doesn't execute my promise as expected and goes into my catch. I sent responses to postman and using res.json(req.user.id) and res.json(profileFields) . This is the response I get when I use
profileFields
{
"user": "5b3134a0e2543b06d130a5d7",
"handle": "wadeaston1",
"status": "Developer",
"skills": [
"HTML",
" CSS",
" Javascipt"
],
"social": {}
}
i'm at a loss here because all my fields are passing in the values as expected into user and $set. I don't understand why its going to my catch
Profile.findByIdAndUpdate(
{ user: req.user.id },
{ $set: profileFields },
{ new: true }
)
.then(profile => res.json(profile))
.catch(err => {
res.json("Timeout");
console.log("HI");
});
Here is my Profile Schema
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
//Create Scheme
const ProfileSchema = new Schema({
user: {
//this will associate user by their ID
type: Schema.Types.ObjectId,
ref: "users"
},
handle: {
type: String,
required: true,
max: 40
},
company: {
type: String
},
website: {
type: String
},
location: {
type: String
},
status: {
type: String,
required: true
},
skills: {
//Array of strings
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,
required: true
},
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,
required: true
},
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);
findByIdAndUpdate is for finding the document to update by its _id value, but you need to find the document by its user field, so you should be using findOneAndUpdate instead:
Profile.findOneAndUpdate(
{ user: req.user.id },
{ $set: profileFields },
{ new: true }
)
.then(...
No need to manually cast req.user.id to an ObjectId as Mongoose will do that for you based on the way user is defined in your schema.
Based on the error you gave, it looks like you need to turn req.user.id from a string to an ObjectId:
Profile.findByIdAndUpdate(
{ user: new mongoose.Types.ObjectId(req.user.id) },
{ $set: profileFields },
{ new: true }
).then( /* rest of code */
This assumes you did a const mongoose = require('mongoose') or similar.

Categories