How to add to array in mongo db collection - node.js

Good evening,
I have my model
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const widgetSchema = new Schema({
city: {
type: String
}
})
const userSchema = new Schema({
name: {
type: String,
},
password: {
type: String
},
widgets: [widgetSchema]
})
const User = mongoose.model('user', userSchema);
module.exports = User;
And my question is how can I add elements to the widget array?
Should I use an update or what?
I think, firstly I need to find user document:
app.post('/addwidget', async (req, res) => {
const { city } = req.body;
try {
const user = await User.findOne({"name": "1"});
}
catch(err){
console.log(err)
}
})
and thank what? Is there method like push or something like that?

Try this one :
try {
const user = await Research.findOneAndUpdate({ name: '1' }, { $push: { widgets: { city: 'viking' }} })
if (user) return user;
else return false;
} catch (error) {
console.log(error);
}

you can use $push or $addToSet to add new item to the widgets array :
app.post('/addwidget', async (req, res) => {
const { city } = req.body; //
try {
const user = await User.findOneAndUpdate({"name": "1"} , { $push: { widgets: city }});
}
catch(err){
console.log(err)
}
})
or :
app.post('/addwidget', async (req, res) => {
const { city } = req.body;
try {
const user = await User.findOneAndUpdate({"name": "1"} , { $addToSet : {widgets: city }});
}
catch(err){
console.log(err)
}
})

From the doc: Adding Subdocs to Arrays, you can use MongooseArray.prototype.push()
E.g.
app.post('/addwidget', async (req, res) => {
const { city } = req.body;
try {
const user = await User.findOne({ name: '1' });
user.widgets.push({ city: 'viking' });
await user.save();
} catch (err) {
console.log(err);
}
});

Related

Cannot push in mongodb

Im trying to create an API where users can create their fav movies and rate them.
So instead of creating a Movies array in user model, I created a Movie model with userId as an array. Now the logic is if there is a movie by the same name the new user is trying to create, it will not create a movie, rather it will push the userid and their rating. If there is no movie by that name it will create one. But I am stuck in that part. Any help will be hugely appreciated. Below im posting my code.
Movie model
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const movieSchema = new Schema({
title: {
type: String,
required: true,
},
rating: [
{ type: Number, required: true, max: 5 },
],
userId: [
{
type: String,
},
],
});
const Movie = mongoose.model(
'Movie',
movieSchema
);
module.exports = Movie;
user model
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const userSchema = new Schema({
name: {
type: String,
required: true,
},
age: {
type: Number,
required: true,
},
// list: {
// type: Array,
// default: [],
// },
});
const User = mongoose.model('User', userSchema);
module.exports = User;
movie route
const router = require('express').Router();
const User = require('../models/User');
const Movie = require('../models/Movies');
//creating a movie
router.post(
'/:id/createmovie',
async (req, res) => {
const { title, rating } = req.body;
const userId = req.params.id;
try {
const currentMovie = await Movie.findOne({
title,
});
if (currentMovie == null) {
const newMovie = new Movie({
title,
rating,
userId,
});
newMovie
.save()
.then((data) => res.json({ data }))
.catch((err) => {
res.status(400).json({ error: err });
});
}
currentMovie
.updateOne(
{ title },
{ $push: { userId, rating } }
)
.then((data) => res.json({ data }))
.catch((err) => {
res.status(400).json({ error: err });
});
} catch (err) {
console.log(err);
}
}
);
// router.post('/:id/createmovie', (req, res) => {
// const { title, rating } = req.body;
// const userId = req.params.id;
// Movie.findOne({ title }).then((data) => {
// console.log(data);
// res.json(data);
// if (data == null) {
// res.send('true');
// }
// res.send('false');
// if (data.title == title) {
// Movie.updateOne(
// { title },
// { $push: { userId, rating } }
// );
// }
// const newMovie = new Movie({
// title,
// rating,
// userId,
// });
// newMovie
// .save()
// .then((data) => res.json({ data }))
// .catch((err) => {
// res.status(400).json({ error: err });
// });
// });
// });
router.get('/getmovie', (req, res) => {
const { title } = req.body;
Movie.find({ title })
.then((data) => res.json(data[0].title))
.catch((err) => {
res.status(400).json({ error: err });
});
});
module.exports = router;
Change router.post function arguments
router.post(
'/:id/createmovie',
async (req, res) => {
const { title, rating } = req.body;
const userId = req.params.id;
try {
const currentMovie = await Movie.findOne({
title,
});
if (currentMovie == null) {
await Movie.insertOne({title ,rating, userId})
.
}
else{
await Movie.updateOne(
{ title },
{ $push: { userId, rating } }
)
}
} catch (err) {
console.log(err);
}
}
);

how do i use find() with mongoose to find by another field

I am trying to find subscriptions by MovieId,or MembeId
this is the schema:
const SubscriptionSchema = new mongoose.Schema({
MovieId : String,
MemberId : String,
Date : Date
})
this is the server:
BL:
const getAllSubscriptionsByMovieId = function(movieid)
{
return new Promise((resolve,reject) =>
{
Subscription.find({MovieId : movieid}, function(err, data)
{
if(err)
{
reject(err)
}
else
{
resolve(data);
}
})
})
}
router:
router.route('/')
.get( async function(req,resp)
{
let data = await subscriptionsBL.getAllSubscriptionsByMovieId(movieid)
return resp.json(data);
})
what is wrong??

MongoDB using NodeJS api return Null why?

I know there is a lot of post about that but none have my problem, my tables exist, the path work to some extent but two of the request just return null and I have no idea why.
Here the request that dont work :
// *Get Chat Message*
router.get("/message/:MessageId",async(req, res)=>{
try{
const message = await Message.findById(req.params.MessageId);
res.status(200).json(message)
} catch (err){
res.status(500).json(err)
}
})
// *Get All Chat Message*
router.get("/message/findAll",async(req, res)=>{
try {
const messages = await Message.find();
res.status(200).json(messages)
} catch (err) {
res.status(500).json(err);
}
})
If need here is the rest of the file where ALL the requests work PERFECTLY so I don't know why only those two don't work.
const router = require("express").Router();
const Post = require("../models/Post");
const User = require("../models/User");
const Chat = require("../models/Chat");
const Message = require("../models/ChatMessage");
// * Get a Chat *
router.get("/:firstUserId/:secondUserId", async(req, res) => {
const chat = await Chat.findOne({ users: { $all: [req.params.firstUserId, req.params.secondUserId] } });
res.status(200).json(chat);
})
// * Get every Chat of one user *
router.get("/:userId", async(req, res) => {
try{
const chats = await Chat.find({ users: { $all: [req.params.userId]} });
res.status(200).json(chats);
}catch(err){
res.status(500).json(err);
}
})
// *Create Chat*
router.post("/",async(req, res)=>{
const chat = new Chat(req.body)
try {
const savedChat = await chat.save();
res.status(200).json(savedChat);
}catch(err){
res.status(500).json(err)
}
})
// *Delete Chat*
router.delete("/:firstUserId/:secondUserId",async(req, res)=>{
const chat = await Chat.findOne({ users: { $all: [req.params.firstUserId, req.params.secondUserId] } });
try{
chat.deleteOne();
res.status(200).json("The chat has been delete successfully.")
} catch (err){
res.status(500).json(err)
}
})
// *Put Chat Message*
router.put("/message",async(req, res)=>{
const newMessage = new Message(req.body)
try {
const savedMessage = await newMessage.save();
res.status(200).json(savedMessage)
} catch (err) {
res.status(500).json(err)
}
})
The schema name and parameter of the database are the same so I don't know why it doesn't work. It still returns null even if I erase the two that don't work, it only returns an error if I delete the whole file.
Here is my schema:
const mongoose = require("mongoose");
const ChatMessageSchema = new mongoose.Schema({
conversationId: {
type: String,
required: true
},
userId: {
type: String,
required: true
},
content: {
type: String,
required: true,
max: 5000
},
state: {
type: Number,
default: 0
}
},
{ timestamps: true }
);
module.exports = mongoose.model("chat_message", ChatMessageSchema,"chat_messages");
The table
Request done in Postman
to get all document use
Model.find({});
and for single try the following
Model.findOne({_id: <id>})
Finaly found the error.
The problem is that for express /message and /message/:MessageId were on the same path.
/findAll still does not work but I don't need it.

When deleting parent record then also delete reference record in mongoose node js || How can i delete reference record when deleting parent record

When i delete course then also delete the reference records of course.
For example i have mca course and it's reference subject is c, java, python when i delete mca also delete the all the reference subject.
How can i do this. Please help
Here is Course.js
const mongoose = require('mongoose');
const Subject = require('./Subject');
const courseSchema = new mongoose.Schema({
course_name: String,
course_semester: Number
})
courseSchema.virtual('subjects', {
ref: 'Subject',
localField: '_id',
foreignField: 'course_id'
})
// Delete subject when course is removed
courseSchema.pre('remove', async function (next) {
const course = this
await Subject.remove({ course_id: course._id })
next()
})
const Course = mongoose.model('Course', courseSchema)
module.exports = Course
Here is Subject.js
const mongoose = require('mongoose');
const subjectSchema = new mongoose.Schema({
subject_code: String,
subject_name: String,
subject_theory_marks: Number,
subject_practicle_marks: Number,
course_id: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Course'
}
})
const Subject = mongoose.model('Subject', subjectSchema)
module.exports = Subject
courseRoute.js
router.get('/admin/delete-course/:id', adminAuthMiddleware,
async (req, res) => {
try {
await Course.findByIdAndRemove(req.params.id, (err, doc) => {
if (!err) {
res.redirect('/admin/view-course');
} else {
res.send('Error in Course delete :' + err);
}
})
} catch (err) {
res.send(err);
}
});
I found solution of this problem.
you need to call remove() in your route
courseRoute.js
router.get('/admin/delete-course/:id', adminAuthMiddleware,
async (req, res) => {
try {
await Course.findByIdAndRemove(req.params.id, (err, doc) => {
if (!err) {
doc.remove() //here is the solution
res.redirect('/admin/view-course');
} else {
res.send('Error in Course delete :' + err);
}
})
} catch (err) {
res.send(err);
}
});

How to update user's profile in express?

I want to update a particular user's financial records which is an array.
<-- This is my user model -->
const FinanceSchema = new mongoose.Schema({
moneyToBePaid: {
type: Number,
},
moneyPaid: {
type: Number,
},
moneyToBeReceived: {
type: Number,
},
moneyReceived: {
type: Number,
},
});
const UserSchema = new mongoose.Schema({
financialInformation: [FinanceSchema],
});
module.exports = mongoose.model("user", UserSchema);
<-- This is my post route -->
router.post("/users/:id/profile", async (req, res) => {
const _id = req.params.id;
const {
moneyToBePaid,
moneyPaid,
moneyToBeReceived,
moneyReceived,
} = req.body;
const finance = {
moneyToBePaid,
moneyPaid,
moneyToBeReceived,
moneyReceived,
};
try {
const user = await User.findById(_id);
user.financialInformation.push(finance);
await user.save();
res.status(200).json(user);
}
<-- This is my update route -->
router.patch("/users/:user_id/profile/:profile_id", async (req, res) => {
const user_id=req.params.user_id;
const profile_id=req.params.profile_id;
try {
}
I am confused how to update a particular user's particular finance record.
Assuming you want to update the moneyPaid property of specific finance array element:
try {
const user_id=req.params.user_id;
const profile_id=req.params.profile_id;
await User.findOneAndUpdate(
{ "_id": user_id, "financialInformation._id": profile_id },
{
"$set": {
"financialInformation.$.moneyPaid": "2258" // the data you want to update
}
});
res.status(200).send('user updated');
} catch(err) {
console.log(err);
res.send(err);
}

Resources