This is how my "Users" databse looks like:
{
"_id" : ObjectId("5f1408d3c0e8c130503daafd"),
"username" : "Akhil Jagga",
"data" : [
{
"_id" : ObjectId("5f15cde9329fc9300c7f3843"),
"nameOfList" : "home",
"items" : [
{
"_id" : ObjectId("5f15cde9329fc9300c7f3844"),
"nameOfItem" : "this is the list item"
}
]
},
{
"_id" : ObjectId("5f15cebd9a97051d80c6c6ad"),
"nameOfList" : "personal",
"items" : [
{
"_id" : ObjectId("5f15cebd9a97051d80c6c6ae"),
"nameOfItem" : "this is the list item"
},
{
"_id" : ObjectId("5f15cfd0d73dc330dc8e7fd1"),
"nameOfItem" : "lol"
}
]
}
],
"__v" : 48
}
I want to delete a specific object from "items" array say with ObjectId("5f15cebd9a97051d80c6c6ae"), using mongoose in nodejs .
I tried by writting the following code but it does't work:
app.post("/delete", redirectLogin, function(req, res) {
const checkedItemId = req.body.checkbox;
const checkedItemName = req.body.hiddenInput;
const listName = req.body.listName;
console.log("item id: " + checkedItemId);
User.findOneAndUpdate(
{
username: req.session.userId
},
{
$pull: {
data: {
items: {
_id: checkedItemId
}
}
}
},
function(err, foundList) {
console.log(foundList);
res.redirect("/");
});
});
I have tried using findOneAndUpdate, if I write name of item with the
id it deletes the whole list from data array containing that item
name and id.
Thankyou for your time.
Try this one,
const username = req.session.userId;
const listName = req.body.listName;
const checkedItemId = req.body.checkbox;
User.update({ "username": username}, { "$pull": { `data.${listName}.items`: { "_id": checkedItemId } }}, { safe: true, multi:true }, function(err, obj) {
//do rest
});
Related
I'm having trouble dealing with populate within object, so I have a SosmedPost schema. I want to populate the Comments field, which is an array. Likewise, I have 2 function create comment and getPost, the populate working in create comment but in getPost it's not working
const SosmedPostSchema = new mongoose.Schema({
Username : {
type : String
},
Content : {
type : String
},
Documents : {
type : String
},
Author : {
type : mongoose.Schema.Types.ObjectId,
ref : 'sosmedprofiles'
},
Comments : [{
PostedBy : {
type : mongoose.Schema.Types.ObjectId,
ref : "sosmedprofiles"
},
Text : {
type : String
}
}],
Likes : [{
type : mongoose.Schema.Types.ObjectId,
ref : "sosmedprofiles"
}]
}, {timestamps : true});
I have a function to create comment, and it's working perfectly fine
const createComment = (req, res) => {
const Id = req.params.id;
const comment = {
Text : req.body.Text,
PostedBy : req.body.PostedBy
}
SosmedPostModel.findByIdAndUpdate({_id : Id}, {
$push : {Comments : comment}
}, {
new : true
}).populate("Comments.PostedBy")
.exec((err, result) => {
if (err) {
return res.status(422).json({error : err})
} else {
res.json(result)
}
})
}
But in another function getPostById the Comments.PostedBy populate its not working. Is there something wrong with how I populate the array ?
const getPostById = (req, res) => {
const Id = req.params.id;
SosmedPostModel.findById({_id : Id})
.populate("Author")
.populate("Comments.PostedBy")
.populate("Likes")
.exec(function (err, posts) {
if (err) return handleError(err);
res.send(posts)
})
}
This is the result in create comment function :
"Comments": [
{
"Text": "Cool Post",
"PostedBy": {
"_id": "63a116dc3c759e4437fabacb",
"Username": "rahmandhika5#gmail.com",
"FullName": "Rahmandhika",
"ProfilePicture": "https://example.jpg",
"Bio": "Live in Tangerang",
"Post": [],
"createdAt": "2022-12-20T01:58:52.179Z",
"updatedAt": "2022-12-20T01:58:52.179Z",
"__v": 0
},
"_id": "63a1172f3c759e4437fabaf9"
},
But in getPostById function, the result is :
"Comments": [
{
"Text": "Cool Post",
"PostedBy": "63a116dc3c759e4437fabacb",
"_id": "63a1172f3c759e4437fabaf9"
},
{
"Text": "Yo",
"PostedBy": "63a116dc3c759e4437fabacb",
"_id": "63a11bab4aad531ee8ad8273"
},
{
"PostedBy": "63a116dc3c759e4437fabacb",
"Text": "YAAY",
"_id": "63a11fcdf5384ab89174ad7e"
}
],
I have a document that looks like this:
{
"_id" : ObjectId("5f55fdede873f132ec09207e"),
"edition_id" : NumberInt(35889464),
"title" : "TEAM ROCKET EDITION",
"date" : "2020-09-19T10:00:00.000+0000",
"homescreen" : {
"image" : "https://media3.giphy.com/media/oOfLwhLyRUoRW/giphy.gif",
"song" : "5T8l7ciAo4H3NGFld8c9Ow"
},
"teams" : [
{
"team_id" : "8675309",
"team_name" : "",
"team_code" : ""
},
{
"team_id" : "7779311",
"team_name" : "",
"team_code" : ""
},
{
"team_id" : "79369254",
"team_name" : "",
"team_code" : ""
}
]
}
I'm trying to form a MongoDB query that will find a matching team_id and update the team_name for that array item. I've tried several things within this structure:
import { connectToDatabase } from 'utils/mongodb';
export default async (req, res) => {
const { db } = await connectToDatabase();
const {
query: { edition_id, team_name, team_id },
} = req;
console.log({ req });
const edition = await db.collection('editions').findOneAndUpdate(
{ edition_id: parseInt(edition_id) },
{
$set: {
},
},
);
res.json(edition);
};
but I can't seem to formulate the right query.
Please check this query,
const edition = await db.collection('editions').updateOne(
{ 'teams.team_id': '8675309' },
{
$set: {
'teams.$.team_name': 'team_name_value'
},
},
);
my Test Schema:
var TestSchema = new Schema({
testName: String,
topic: {
topicTitle: String,
topicQuestion: [
{
questionTitle: String,
choice: [
{
name: String
age: Number
}
]
}
]
}
}, { collection: 'test' });
var Test = mongoose.model('test', TestSchema);
I want to update one age ($inc)value which I have the choice id.
I can have test id, topicQuestion id and choice id.
How to write this query in mongoose in NodeJS?
Normally I use the below query to update a value:
Test.findOneAndUpdate({ _id: testId }, { $inc: { ... } }, function (err, response) {
...
});
but it is so difficult to get in array and one more array. Thanks
You can use the $[] positional operator to update nested arrays.
router.put("/tests/:testId/:topicQuestionId/:choiceId", async (req, res) => {
const { testId, topicQuestionId, choiceId } = req.params;
const result = await Test.findByIdAndUpdate(
testId,
{
$inc: {
"topic.topicQuestion.$[i].choice.$[j].age": 1
}
},
{
arrayFilters: [{ "i._id": topicQuestionId }, { "j._id": choiceId }],
new: true
}
);
res.send(result);
});
Let's say we have this existing document:
{
"_id" : ObjectId("5e53e7d9bf65ac4f5cbf2116"),
"testName" : "Test 1",
"topic" : {
"topicTitle" : "Title",
"topicQuestion" : [
{
"_id" : ObjectId("5e53e7d9bf65ac4f5cbf211a"),
"questionTitle" : "Question 1 Title",
"choice" : [
{
"_id" : ObjectId("5e53e7d9bf65ac4f5cbf211c"),
"name" : "A",
"age" : 1
},
{
"_id" : ObjectId("5e53e7d9bf65ac4f5cbf211b"),
"name" : "B",
"age" : 2
}
]
},
{
"_id" : ObjectId("5e53e7d9bf65ac4f5cbf2117"),
"questionTitle" : "Question 2 Title",
"choice" : [
{
"_id" : ObjectId("5e53e7d9bf65ac4f5cbf2119"),
"name" : "C",
"age" : 3
},
{
"_id" : ObjectId("5e53e7d9bf65ac4f5cbf2118"),
"name" : "D",
"age" : 4
}
]
}
]
},
"__v" : 0
}
If we want to increment age value of a given choice, we send a PUT request using endpoint like this http://.../tests/5e53e7d9bf65ac4f5cbf2116/5e53e7d9bf65ac4f5cbf211a/5e53e7d9bf65ac4f5cbf211b where
"testId": "5e53e7d9bf65ac4f5cbf2116"
"topicQuestionId": "5e53e7d9bf65ac4f5cbf211a"
"choiceId": "5e53e7d9bf65ac4f5cbf211b"
You need to inform what choice you want and, on the update section, you need change the way you do increment.
Example:
Test.findOneAndUpdate({ _id: testId, topicQuestion.choice._id: choiceId}, { 'topicQuestion.$.choice': {$inc: { age: <numberToIncrement> }}}, {new: true}, function (err, response) {
...
});
Hello I am trying to delete pushed (data) _id from a document array, but I am getting no response while executing.
Also, since it is a relational _id which I am trying to delete. How can I delete from the collection it is actually stored ?
here is my delete route:-
router.delete('/userDelete/:userId', checkAuth , (req, res, next) =>{
if(req.userData.role2 === 'admin') {
Admin.findOneAndDelete({_id: req.params.userId},{ $pull: { 'admins.users': {_id: req.params._id}}},{new: true})
.exec()
.then(result => {
res.status(200).send(["Deleted"]);
})
.catch(err =>{
if (err.code == 500)
res.status(500).send(["Didn't get deleted"]);
else
return next(err);
});
}else{
res.send(["Unauthorized. Not deleted"]);
}
});
This is the nested object looks like :-
{
"admins": {
"users": [
"5d0364048db4957100f33fea" //<===want to delete this relational id
],
"email": "1cf1eede89#himail.online",
"password": "$2a$10$vHyGxX9P.t0/ybKcmIzkc.ZCX18oHaVnvTgJIWA2gTNzJ3TCdXS4a",
"_id": "5d0339d5b4b28b6ddff06802",
"companyName": "GH",
"__v": 0
}
This is my controller :-
var admin = new Admin();
admin.companyName = req.body.companyName;
admin.admins = {
email : req.body.email,
password: req.body.password,
users : []
};
Is is also possible to delete records from each and every collections where particular _id data is located ?
You need to find the Document and update,
Data
{
"_id" : "5d0339d5b4b28b6ddff06802",
"admins" : {
"users" : [
"5d0364048db4957100f33fea"
]
}
}
Query
db.users.updateOne(
{ _id: req.params.userId },
{
$pull: {
"admins.users": req.params._id
}
}
);
Result
{
"_id" : "5d0339d5b4b28b6ddff06802",
"admins" : {
"users" : [ ]
}
}
I tried to remove an object from document array but something not working:
This is my object:
{
"_id" : ObjectId("5b487aa1427e5a1edc1cdbac"),
"location" : {
"latitude" : 0,
"longitude" : 0
},
"email" : "ran#gmail.com",
"firstName" : "Ran",
"lastName" : "Alcobi",
"interests" : [
ObjectId("5b49a44bc3b19929b098547e")
],
}
I removed Interest from the interests collection and I need that the interest will be removed from the Interests array of the user:
this is my code:
router.delete('/:id', (req, res) => {
var id = req.params.id;
if (!ObjectID.isValid(id)) {
return res.status(404).send();
}
Interest.findOneAndRemove({
_id: id,
}).then((interest) => {
if (!interest) {
return res.status(404).send();
}
User.update(
{$pull:
{interests: {$in : interest._id} }
},
{multi: true},
).then((user) => {
console.log(user);
res.send({interest});
}).catch((e) => {
res.status(400).send();
});
});
});
Thanks a lot for helpers. I would be happy to know what is my mistake.
You are passing $pull in wrong parameter of update query... In update query first parameter is for filter and second parameter is for update operation... So you have to first filter with $in and then $pull from the interest array...
So, finally you need to do something like this
User.update(
{ interests: { $in : [interest._id] } },
{ $pull: { interests: interest._id } }
{ multi: true },
)