Here's my object:
{
posts: [
{
_id: 603dd892548e9b30201cb254,
title: '222222222',
content: '222222222',
__v: 0
},
{
_id: 603df0a5996e422c6cbd05d6,
title: 'ANdrew',
content: 'testestetsetste',
__v: 0
},
{
_id: 603df53790787539a8c92472,
title: 'vvvvvvvvvvvvvvvvvvv',
content: 'vvvvvvvvvvvvvvvvvvvvvvvvvv',
__v: 0
},
{
_id: 603e2abfa384381c28529c76,
title: 'qqqqqqqqqqqqqq',
content: 'qqqqqqqqqqqqqqqqqq',
__v: 0
},
{
_id: 603e2b36550cd6289caa880b,
title: '333',
content: '333',
__v: 0
}
],
_id: 603dd326b8c54d1ac0afea0f,
username: 'andrew',
mail: 'mail#gmail.com',
__v: 5
}
From array "posts" I wanna delete any item I want, so I did:
User.findByIdAndUpdate(req.user.id, {$pull: {posts: { _id: postID}}}, function(err, obj) {
if(!err){
res.redirect("/")
} });
Page refreshes, but every note is still there. What's going on? i tried updateOne too, and object.notes.pull({_id: postID}). All without errors as well as without deletions.
Related
My code was working well when i was using findById. I want to make slug so i used mongoose-slug-generator. and i used find to get the data from the Database.
The problem is i get the data back while using find method but i cannot access it as a JavaScript Object.
data returned by find method
{
category: [
{
subCategory: [Array],
product: [Array],
_id: 60e14e0994e27f3a2c93a26a,
category: 'Electronics',
image: 'images\\2021-07-04T05-58-33.034Z-download.jpg',
createdAt: 2021-07-04T05:58:33.108Z,
updatedAt: 2021-08-31T13:35:12.140Z,
__v: 0
}
],
subCategory: [
{
category: [Array],
product: [Array],
_id: 60e14e2294e27f3a2c93a26c,
subCategory: 'Laptop',
createdAt: 2021-07-04T05:58:58.554Z,
updatedAt: 2021-08-31T13:35:12.142Z,
__v: 0
}
],
brand: [
{
product: [Array],
_id: 60e14e6294e27f3a2c93a271,
brand: 'sound',
image: 'images\\2021-07-04T06-00-02.355Z-brand_4.png',
createdAt: 2021-07-04T06:00:02.370Z,
updatedAt: 2021-08-31T13:35:12.145Z,
__v: 0
}
],
rating: [],
sellCount: '0',
color: [ 'blue' ],
size: [ 'LG' ],
image: [ 'images\\2021-08-31T13-35-12.116Z-hac-hdbw1231ra-z-a.png' ],
_id: 612e3010abd51525286ea7e9,
title: 'CCTV DAUHA HD 2.0 MP camera for security test2',
description: 'THis is discription',
price: 200,
discount: 2,
quantity: 200,
feature: false,
active: true,
stock: true,
createdAt: 2021-08-31T13:35:12.130Z,
updatedAt: 2021-08-31T13:35:12.130Z,
slug: 'cctv-dauha-hd-2-0-mp-camera-for-security-test2-rTfwYsVts',
__v: 0
}
controller
exports.getSingleProduct = (req, res, next) => {
let slug = req.params.slug
Product.find({slug: slug})
.populate("category")
.populate("subCategory")
.populate("brand")
.populate({
path: 'rating',
populate: {
path: 'user',
model: 'User'
}
})
.then((product) => {
console.log("controller" + product.title)
let brandId =product.brand[0].id
Product.find({ brand: brandId })
.then((brand) => {
res.render("user/single-product", {
product,
user: sessionUser,
featured: req.featured,
categories: req.categories,
related: req.related,
brand,
bestSeller: req.bestSeller,
banner: req.banner,
mostRated: req.mostRated,
storelists: req.storelists,
});
})
.catch((err) => {
console.log(err);
})
})
.catch((err) => {
console.log(err)
})
}
code use to work but not working now
console.log("controller" + product.title)
used to work when there was finById method used.
what is the problem? thank you
I have mongoose collection "travels" with data like below. In data there is 3 items with same nUid but lastUpdateTime is different for each entry.
[
{
_id: 5ffff2bc9698ce3514ef6d5a,
nUid: 123456,
latitude: '19.154607',
longitude: '72.936027',
name: 'abc1',
lastUpdateTime: 2021-01-14T07:26:51.000Z,
__v: 0
},
{
_id: 5fffeca4794ca00ae85ee940,
nUid: 635241,
latitude: '19.154620',
longitude: '72.936087',
name: 'abc2',
lastUpdateTime: 2021-01-14T03:31:20.000Z,
__v: 0
},
{
_id: 5fffeca4794ca00ae85ee93f,
nUid: 123456,
latitude: '19.154609',
longitude: '72.936047',
name: 'abc1',
lastUpdateTime: 2021-01-14T09:20:23.000Z,
__v: 0
},
{
_id: 5ffff2bc9698ce3514ef6d59,
nUid: 123456,
latitude: '19.154620',
longitude: '72.936087',
name: 'abc1',
lastUpdateTime: 2021-01-14T10:38:20.000Z,
__v: 0
},
{
_id: 5ffff4610fd21902e02ac749,
nUid: 345262,
latitude: '19.154620',
longitude: '72.936087',
name: 'abc3',
lastUpdateTime: 2021-01-14T09:11:30.000Z,
__v: 0
},
{
_id: 5ffff4610fd21902e02ac748,
nUid: 635241,
latitude: '19.154640',
longitude: '72.936017',
name: 'abc2',
lastUpdateTime: 2021-01-14T04:30:10.000Z,
__v: 0
},
]
I want to sort data like common ids with latest lastUpdateTime
[
{
_id: 5ffff2bc9698ce3514ef6d59,
nUid: 123456,
latitude: '19.154620',
longitude: '72.936087',
name: 'abc1',
lastUpdateTime: 2021-01-14T10:38:20.000Z,
__v: 0
},
{
_id: 5ffff4610fd21902e02ac748,
nUid: 635241,
latitude: '19.154640',
longitude: '72.936017',
name: 'abc2',
lastUpdateTime: 2021-01-14T04:30:10.000Z,
__v: 0
},
{
_id: 5ffff4610fd21902e02ac749,
nUid: 345262,
latitude: '19.154620',
longitude: '72.936087',
name: 'abc3',
lastUpdateTime: 2021-01-14T09:11:30.000Z,
__v: 0
},
]
Tried solution
const travelsQuery = Travels.aggregate([
{ $group: { _id: "$nUid", result: { "$first": "$$ROOT" } } },
{ $sort: { lastUpdateTime: 1 } }]);
const travelsData= await travelsQuery;
let travelsResult= travelsData.map((travel) => {
return travel.result;
});
But not getting proper result, I got data with same ids but not sorted by lastUpdateTime, I tried lastUpdateTime: -1` also.
Thanks in advance :)
You copied the document into result so try:
const travelsQuery = Travels.aggregate([
{ $group: { _id: "$nUid", result: { "$first": "$$ROOT" } } },
{ $sort: { "result.lastUpdateTime": 1 } }]);
const travelsData= await travelsQuery;
let travelsResult= travelsData.map((travel) => {
return travel.result;
});
After updating $first to $last It's working as required :)
const travelsQuery = Travels.aggregate([
{ $group: { _id: "$nUid", result: { "$last": "$$ROOT" } } },
{ $sort: { "result.lastUpdateTime": 1 } }]);
const travelsData= await travelsQuery;
let travelsResult= travelsData.map((travel) => {
return travel.result;
});
The given below is my document, I need to remove comments array of an object from the document, so I can pass the document id from the frontend, with postId.
I am struct please help me.
{
likes: [],
_id: 5ea4375f49e4355094073330,
title: 'abc',
body: 'abc',
photo: 'no pic',
postedBy: 5e9aa457de91831e5c9f5005,
comments: [
{
_id: 5ea437c2a584ce5ac0147da1,
text: 'sadsadsad',
postedBy: [Object]
},
{
_id: 5ea437c5a584ce5ac0147da2,
text: 'sadsadsad',
postedBy: [Object]
},
{
_id: 5ea437c7a584ce5ac0147da3,
text: 'sadsadsad',
postedBy: [Object]
}
],
__v: 0
}
If you want to remove a specific element from the array of comments you can use the following query:
db.mycollection. updateOne(
{'_id': ObjectId("5ea4375f49e4355094073330")},
{ $pull: { "comments" : { _id: ObjectId("5ea437c2a584ce5ac0147da1") } } }
);
If you want to remove comment object from every element in your collection you can simply remove the first argument from update. Something like this:
db.mycollection.updateMany(
{ },
{ $pull: { "comments" : { _id: ObjectId("5ea437c2a584ce5ac0147da1") } } }
);
I have a mongoose query that should fetch all Participants in certain Event model, but I only get back one participant. I tried the $all method, still no result.
query:
Participants.find({'_id': {$all: event.participants}}, (err, participants) => {
if (err) {
return console.log(err);
}
console.log(participants);
});
output:
[ { createdAt: 1970-01-01T00:00:00.011Z,
_id: 5be7fc340016817bcb4ybdfc,
name: 'TEST',
ticket: 5be7fc340016817bc44fbdfb,
email: 'test#test.com',
__v: 0 } ]
expected output
[ { createdAt: 1970-01-01T00:00:00.011Z,
_id: 5be7fc340016817bcb4fbdfc,
name: 'TEST',
ticket: 5be7fc3400d16817bcb4fbdfb,
email: 'rene370d#gmail.com',
__v: 0 },
{ createdAt: 1970-01-01T00:00:00.011Z,
_id: 5be7fc340016817bcb4fbdfc,
name: 'Another test',
ticket: 5be7fc3s40016817bcb4fbdfb,
email: 'another#emai.com',
__v: 0 } ]
event.participants
participants:{
type: [mongoose.Schema.Types.ObjectId],
ref: 'ParticipantSchema'
}
From the documentation:
The $all operator selects the documents where the value of a field is an array that contains all the specified elements.
So it doesn't make much sense to use it to get all documents for a certain model.
Instead, use the $in operator
Participants.find({ _id: { $in: event.participants } }, (err, participants) => {
if (err) {
return console.log(err);
}
console.log(participants);
});
I'm trying to setup a delete button where a lesson can be deleted from a class. Using $pull seems to just set lesson_id to null though. Is there a way to remove that element completely?
var classSchema = new Schema({
title: { type: String, required: true },
lessons: [{
_id: false,
lesson_id: {type: mongoose.Schema.Types.ObjectId, ref: 'Lesson'}
}]
});
module.exports.deleteLesson = function(class_id, lesson_id, callback){
Class.update(
{'_id': class_id},
{ $pull: {lessons: {'lesson_id.$._id': lesson_id}}},
callback
)
}
For example
{ _id: 5808,
title: 'cd',
__v: 0,
lessons: [ { lesson_id: [Object] }, { lesson_id: [Object] } ] }
becomes
{ _id: 5808,
title: 'cd',
__v: 0,
lessons: [ { lesson_id: null }, { lesson_id: [Object] } ] }
If you need to delete an element from lessons (which is an array), then you need to just perform the deletion of element from the array and then perform a save operation. I have written code showcasing a similar approach.
Class.findOne({ _id: class_id }, function(err, cls) {
# Delete the element (for example, using underscore)
cls.lessons = _.without(cls.lessons, class_id);
cls.save(function (err) {
callback(err);
});
});