I want to update the type: reported to type: pending under the reportStatus, but when I try it on postman I keep on getting
n:1 ,n:modified:1 and ok:1
report: [
{
category: {
type: mongoose.Schema.Types.ObjectId,
ref: "CrimeCategory",
required: true,
},
location: {
type: mongoose.Schema.Types.ObjectId,
ref: "Location",
required: true,
},
reportText: {
type: String,
required: true,
},
reportStatus: {
type: mongoose.Schema.Types.Mixed,
default: function () {
return [
{ type: "reported", date: new Date(), isCompleted: true },
{ type: "pending", isCompleted: false },
{ type: "investigating", isCompleted: false },
{ type: "solved", isCompleted: false },
];
},
},
},
],
This is the controller where I am trying to update the types that is in the model, what am I doing wrong?
const crimeReport = require("../../model/crimereport");
exports.updateReport = (req, res) => {
crimeReport
.updateOne(
{ _id: req.body.reportId, "report.reportStatus": req.body.type },
{
$set: {
"report.reportStatus.$": [
{
type: req.body.type,
date: new Date(),
isCompleted: true,
},
],
},
}
)
.exec((error, report) => {
if (error) return res.status(400).json({ error });
if (report) {
res.status(200).json({ report });
}
});
};
The postman post request:
{
"reportId": "607b2b25876fa73ec4437440",
"type":"pending"
}
This is the post result from postman:
{
"report": {
"n": 0,
"nModified": 0,
"ok": 1
}
}
It seems like, you are sending reportId in the body of post request as a string while the Mongodb document's id is of type ObjectId. You need to typecast the reportId into ObjectId, before querying to Mongodb. Since you are using Mongoose, this is the way it should be done:
mongoose.Types.ObjectId(req.body.reportId)
Related
I need to run the query by find like I pass id and data only with that Id will display but the issue is it's showing all data means it's not filtering.
I am finding data like this
router.get('/getannouncementsbyrestaurant/:id', async (req, res) => {
let getannouncementsbyrestaurant = await Announcements.find({ restaurants: req.params.id }).populate(['announcementRestaurants']);
if (!getannouncementsbyrestaurant) {
return res.status(400).json({ success: false, message: "something went wrong" })
}
res.status(200).json({ success: true, data: getannouncementsbyrestaurant })
})
and here is the model
const mongoose = require('mongoose');
const announcementsschema = new mongoose.Schema({
announcementName: {
type: String,
required: true
},
announcementDescription: {
type: String,
required: true
},
announcementCountry: {
type: String,
required: false
},
announcementCity: {
type: String,
required: false
},
announcementStreet: {
type: String,
default: ''
},
announcementRestaurants: {
type: mongoose.Schema.Types.ObjectId,
required: true,
ref: 'restaurants'
},
announcementCreatedOn: {
type: Date,
default: Date.now
}
})
announcementsschema.virtual('id').get(function () {
return this._id.toHexString();
});
announcementsschema.set('toJSON', {
virtuals: true,
});
exports.Announcements = mongoose.model('Announcements', announcementsschema);
exports.announcementsschema = announcementsschema;
Don't know why its showing all data
here is example json
"data": [
{
"_id": "631a4c9c2c4fca7afc0f23f5",
"announcementName": "Mega Sale 10% off",
"announcementRestaurants": {
"_id": "631a4af62c4fca7afc0f238f",
"restaurantName": "Mega Restaurant",
},
"id": "631a4c9c2c4fca7afc0f23f5"
},
{
"_id": "631a51b72c4fca7afc0f2449",
"announcementName": "Sale upto 90%",
"announcementRestaurants": {
"_id": "631a51752c4fca7afc0f2434",
"restaurantName": "McDonalds",
},
"announcementCreatedOn": "2022-09-08T20:33:59.870Z",
"__v": 0,
"id": "631a51b72c4fca7afc0f2449"
}
]
I am passing announcementRestaurants._id in param and need to filter with that.
Your schema doesn't have the field restaurants. The corresponding field is announcementRestaurants. So the query should be:
let getannouncementsbyrestaurant =
await Announcements.find({ announcementRestaurants: req.params.id }).populate(['announcementRestaurants']);
Or
let getannouncementsbyrestaurant =
await Announcements.find({ announcementRestaurants: mongoose.Types.ObjectId(req.params.id) }).populate(['announcementRestaurants']);
I've taken up the job from another freelancer who isn't currently engaged on this project.
He has done some work which I don't understand. Can anyone help me with that.
Every time a user hires a parking spot, I want to notify a merchant.
here is the query to create a booking:
exports.createBooking = async (req, res) => {
try {
const user = await Auth.findOne({ _id: req.data.id });
if (!user) return res.status(404).json({ error: "User not found" });
const bookingDetails = new Booking({
userId: req.data.id,
parkingId: req.body.parkingId,
duration: req.body.duration,
date: moment(req.body.date).format("MMM DD, YYYY"),
startTime: req.body.startTime,
endTime: req.body.endTime,
paymentAmount: req.body.paymentAmount,
isFeePaid: req.body.isFeePaid,
status: "sent",
});
bookingDetails.populate("walkerId");
const save = await bookingDetails.save();
// send notification to walker
let notification_data = {
name: `${owner.basicInfo.fullName}`,
date: moment(req.body.date).format("MMM DD, YYYY"),
startTime: req.body.startTime,
};
let { title, body } = notificationTypes.addBooking(notification_data);
let data = {
senderId: req.data.id,
receiverId: req.body.walkerId,
notificationSendTo: "walker",
title,
body,
};
sendNotification(data);
return res.status(200).json({
success: true,
msg: "Service Booked",
data: { details: save },
});
} catch (error) {
return res.status(500).json({ error: error.message });
}
};
And the booking schema looks like this:
const bookingSchema = new mongoose.Schema(
{
parkingId: {
type: mongoose.Schema.Types.ObjectId,
ref: "Parking",
},
userId: {
type: mongoose.Schema.Types.ObjectId,
ref: "Auth",
},
duration: {
type: String,
},
date: {
type: String,
},
startTime: {
type: Date,
},
endTime: {
type: Date,
},
isFeePaid: {
type: Boolean,
default: false,
},
status: {
type: String,
enum: [
"confirmed",
"sent",
"pending",
"accepted",
"rejected",
"cancelled",
"start",
"completed",
],
},
isBookingCancelled: {
cancelBy: {
type: mongoose.Schema.Types.ObjectId,
ref: "User",
},
value: {
type: Boolean,
default: false,
},
cancellationReason: {
type: String,
maxlength: 255,
trim: true,
},
},
paidAmount: {
type: Number,
},
paymentId: {
type: mongoose.Schema.Types.ObjectId,
ref: "Payment",
},
paymentAmount: {
type: Number,
},
isStarted: {
type: Boolean,
default: false,
},
isEnabled: {
type: Boolean,
default: false,
},
},
{
timestamps: true,
}
);
I am aware that the schema lacks a walkerId, which would cause an error to be thrown, but I have never used walker thus I have no idea how to incorporate it.
I'm quiet new to mongodb and I'm actually trying to implement a follow-unfollow method in the backend
there are two types of users in the database
Mentors and mentees
only mentees can follow the mentors and mentors can only accept the request
the schema
Mentors
const MentorsSchema = mongoose.Schema({
name: { type: String, required: true },
designation: { type: String, required: true },
yearNdClass: {
type: String,
required: ["true", "year and class must be spciefied"],
},
respondIn: { type: String, required: true },
tags: {
type: [String],
validate: (v) => v == null || v.length > 0,
},
socialLinks: {
github: { type: String, default: "" },
twitter: { type: String, default: "" },
facebook: { type: String, default: "" },
instagram: { type: String, default: "" },
},
watNum: { type: Number, required: true },
email: { type: String, required: true, unique: true },
password: { type: String, required: true },
about: { type: String },
followers: [
{ type: mongoose.Schema.Types.ObjectId, ref: "Mentees", default: "" },
],
pending: [
{ type: mongoose.Schema.Types.ObjectId, ref: "Mentees", default: "" },
],
});
Mentee
const MenteeSchema = mongoose.Schema({
name: { type: String, required: true },
email: { type: String, required: true, unique: true },
password: { type: String, required: true },
yearNdClass: {
type: String,
required: ["true", "year and class must be spciefied"],
},
socialLinks: {
github: { type: String },
twitter: { type: String },
facebook: { type: String },
instagram: { type: String },
},
about: { type: String },
skillLooksFor: { type: String, required: true },
watNum: { type: Number, required: true },
following: [{ type: mongoose.Schema.Types.ObjectId, ref: "Mentors",default:"" },
],
});
you can see that there are two fields for mentors both following and pending arrays which consist of the ids of the mentees who follow the mentors and the ids of the mentees which yet to be accepted as a follower
I planned to create an endpoint where when a mentee gives a follow request it should be reached into the mentor pending array so that he can accept it later
so my logic like this
// #desc follow a mentor
// #route POST /api/mentees/follow-mentor/:id
// #access private
menteeRoute.post(
"/follow-mentor/:id",
isAuthorisedMentee,
expressAsyncHandler(async (req, res) => {
const { id } = req.params;
const mentee = await Mentees.findById(req.mentee.id);
const mentor = await Mentors.findById(id).select("-password");
// console.log(mentor)
if (mentee) {
try {
await Mentees.findOneAndUpdate(
{ _id: mongoose.Types.ObjectId(id) },
{ $addToSet: { "following.0": mentor._id } },
{ new: true }
);
await Mentors.findOneAndUpdate(
{ _id: mongoose.Types.ObjectId(mentor._id) },
{
$addToSet: {
"pending.0": id,
},
},
{ new: true },
);
res.json({
data: {
mentor,
mentee,
},
});
} catch (error) {
console.log(error);
throw new Error(error);
}
}
})
);
but the code didn't work.
can anyone help me to resolve the problem?
basically, when a mentee gives a follow request it should update the following array of mentee with the id of mentor and it should also update the pending array of mentor with the id of the mentee
PS: any alternative ideas are also welcome
Try to remove the .0 index and use the $push method.
Also, you should return the updated objects:
menteeRoute.post(
'/follow-mentor/:id',
isAuthorisedMentee,
expressAsyncHandler(async (req, res) => {
const { id } = req.params;
const mentee = await Mentees.findById(req.mentee.id);
const mentor = await Mentors.findById(id).select('-password');
// console.log(mentor)
if (mentee) {
try {
const updatedMentee = await Mentees.findOneAndUpdate(
{ _id: mongoose.Types.ObjectId(id) },
{ $push: { following: mentor._id } },
{ new: true }
);
const updatedMentor = await Mentors.findOneAndUpdate(
{ _id: mentor._id },
{
$push: {
pending: id,
},
},
{ new: true }
);
res.json({
data: {
mentor: updatedMentor,
mentee: updatedMentee,
},
});
} catch (error) {
console.log(error);
throw new Error(error);
}
}
})
);
how can I update many orderStatus instead of only one?
request.body.type is by default string and contains only one type;
and when isCompleted for the type go true I want even for previous enum index isCompleted go true
is it possible or do I need to modify it in the front-end?
here is the code
const orderSchema = new mongoose.Schema(
{
user: {
type: mongoose.Schema.Types.ObjectId,
ref: "User",
required: true,
},
orderStatus: [
{
type: {
type: String,
enum: ["ordered", "packed", "shipped", "delivered"],
default: "ordered",
},
date: {
type: Date,
},
isCompleted: {
type: Boolean,
default: false,
},
},
],
}
exports.updateOrder = (req, res) => {
Order.updateOne(
{ _id: req.body.orderId, "orderStatus.type": req.body.type },
{
$set: {
"orderStatus.$": [
{ type: req.body.type, date: new Date(), isCompleted: true },
],
},
}
).exec((error, order) => {
Hey You can use updateMany() operation
db.collection.updateMany(
<query>,
{ $set: { status: "D" }, $inc: { quantity: 2 } },
...
)
I am using comment array in my schema as fallows. I want to push comments data into that comment array using nodejs api
var Schema = mongoose.Schema;
var myfeeds = new Schema({
title: {
type: String,
required: true
},
feed: {
type: String,
required: true
},
createdBy: {
type: String,
required: true,
unique: true
},
createdDate: {
type: Date,
required: true,
default: Date.now()
},
comment: [
{
commentBy: {
type: String
},
commentText: {
type: String
},
createdDate: {
type: Date
}
}
],
likes: [
{
likesCount: {
type: Number,
required: false
},
likeBy: {
type: String,
required: false
}
}
]
});
I want to push object to this comment array. so, for that I did in this way please tell me if anything wrong in this
let _id = req.body.id;
let commentBy = req.body.commentedBy;
let commentedText = req.body.commentedText;
let commentedDate = req.body.commentedDate;
let data = {
commentBy: commentBy,
commentText: commentedText,
createdDate: commentedDate
};
MyFeeds.findByIdAndUpdate(
{ _id: _id },
{
$push: {
comment: data
}
}
)
.then((result) => {
res.status(200).json({
status: result
});
})
.catch((err) => {
res.status(500).json({
status: 'invalid',
err: err
});
});
but only id are inserted into that comment array but not the required content
"comment": [
{
"_id": "5badfd092b73fa14f4f0aa7c"
},
{
"_id": "5badfd102b73fa14f4f0aa7d"
},
{
"_id": "5badfd142b73fa14f4f0aa7e"
},
{
"_id": "5badfd31500fb11bb06b4c8a"
},
{
"_id": "5badfd35500fb11bb06b4c8b"
},
{
"_id": "5badff3d439a151190d62961"
}
],