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
Related
I'm trying to fetch data from below mongoose schema, But I'm not sure how to fetch the role field, which is a type of RoleObject.
import * as mongoose from 'mongoose';
const Schema = mongoose.Schema;
const RoleObject = {
current_role: {
type: Schema.Types.ObjectId,
ref: 'Role',
autopopulate: true
},
new_role: {
type: Schema.Types.ObjectId,
ref: 'Role',
autopopulate: true
}
}
const UserRequestSchema = new mongoose.Schema({
group: {
type: Schema.Types.ObjectId,
ref: 'Group',
autopopulate: true,
required: true
},
user: {
type: Schema.Types.ObjectId,
ref: 'User',
autopopulate: true,
required: true
},
role: {
type: RoleObject
},
status: {
type: String,
required: true,
enum: ['pending', 'approved', 'denied']
},
type: {
type: String,
required: true,
enum: ['group-join', 'role-change']
},
active: {
type: Boolean,
required: true
}
});
UserRequestSchema.index( { group: 1, user: 1 }, { unique: true } );
export { UserRequestSchema };
Here I want populate the role field from the UserRequestSchema, which is given as RoleObject.
Is it possible through populate the field using find method or do I need to use aggregation ?
Try this
UserRequest.find({active:true}).populate({
path: 'role.current_role role.new_role',
model: 'Role',
select: 'name'
}).exec((error, result) => {
if (error) {
console.log(error, " ERROR")
}
console.log(result, "Result")
});
If you face any issue. Please let me know
order.js
const mongoose = require('mongoose');
const orderSchema = mongoose.Schema({
orderItems: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'OrderItem',
required:true
}],
shippingAddress1: {
type: String,
required: true,
},
shippingAddress2: {
type: String,
},
city: {
type: String,
required: true,
},
zip: {
type: String,
required: true,
},
country: {
type: String,
required: true,
},
phone: {
type: String,
required: true,
},
status: {
type: String,
required: true,
default: 'Pending',
},
totalPrice: {
type: Number,
},
user: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User',
},
dateOrdered: {
type: Date,
default: Date.now,
},
})
orderSchema.virtual('id').get(function () {
return this._id.toHexString();
});
orderSchema.set('toJSON', {
virtuals: true,
});
exports.Order = mongoose.model('Order', orderSchema);
order-item.js
const mongoose = require('mongoose');
const orderItemSchema = mongoose.Schema({
quantity: {
type: Number,
required: true
},
product: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Product'
}
})
exports.OrderItem = mongoose.model('OrderItem', orderItemSchema);
orders.js
router.post('/', async (req,res)=>{
const orderItemsIds = Promise.all(req.body.orderItems.map(async (orderItem) =>{
let newOrderItem = new OrderItem({
quantity: orderItem.quantity,
product: orderItem.product
})
newOrderItem = await newOrderItem.save();
return newOrderItem._id;
}))
const orderItemsIdsResolved = await orderItemsIds;
let order = new Order({
orderItems: orderItemsIdsResolved,
shippingAddress1: req.body.shippingAddress1,
shippingAddress2: req.body.shippingAddress2,
city: req.body.city,
zip: req.body.zip,
country: req.body.country,
phone: req.body.phone,
status: req.body.status,
totalPrice: totalPrice,
user: req.body.user,
})
order = await order.save();
if(!order)
return res.status(400).send('the order cannot be created!')
res.send(order);
})
const orderItemsIds = Promise.all(req.body.orderItems.map(async (orderItem) =>{
^
TypeError: Cannot read properties of undefined (reading 'map')
How to solve this error? could anyone please help me to find the error I can't find it I have tried in many ways but I failed to solve this.
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.
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)
}
})
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
}
});