assume i have an document
{ _id: 5e53c14c561efe357053a818,
convoId: 5e53c14c561efe357053a816,
message:
[ { isRead: true,
createdAt: 2020-02-24T12:27:56.085Z,
_id: 5e53c14c561efe357053a819,
senderId: 5e4e50a5ae51b02f08f174eb,
recieverId: 5e4ae76bd4e24418a020b665,
body: 'hiii' },
{ isRead: true,
createdAt: 2020-02-24T12:29:12.333Z,
_id: 5e53c198561efe357053a81c,
senderId: 5e4e50a5ae51b02f08f174eb,
recieverId: 5e4ae76bd4e24418a020b665,
body: 'jawab de' },
{ isRead: true,
createdAt: 2020-02-24T15:17:12.954Z,
_id: 5e53e8f8d22dd714ac7f1ee1,
senderId: 5e4e50a5ae51b02f08f174eb,
recieverId: 5e4ae76bd4e24418a020b665,
body: 'hi again' },
{ isRead: true,
createdAt: 2020-02-25T21:07:15.695Z,
_id: 5e558c8367d9d61e2c52d0db,
senderId: 5e4ae76bd4e24418a020b665,
recieverId: 5e4e50a5ae51b02f08f174eb,
body: 'whats up??' },
{ isRead: true,
createdAt: 2020-02-25T21:11:20.653Z,
_id: 5e558d7867d9d61e2c52d0dc,
senderId: 5e4ae76bd4e24418a020b665,
recieverId: 5e4e50a5ae51b02f08f174eb,
body: 'yoyoy' },
{ isRead: false,
createdAt: 2020-02-25T21:12:30.743Z,
_id: 5e558dbe67d9d61e2c52d0dd,
senderId: 5e4e50a5ae51b02f08f174eb,
recieverId: 5e4ae76bd4e24418a020b665,
body: 'nothing much' } ],
__v: 0 }
i want an array in which senderId is equal to 5e4e50a5ae51b02f08f174eb
here what i have done so far
const message = await Message.findOne({
"message.senderId": "5e4e50a5ae51b02f08f174eb",
});
but am getting whole result basically i want to filter message array with only 5e4e50a5ae51b02f08f174eb this senderId
i can also done with this
const updatedMessage = message.message.filter(msg => {
return msg.senderId == "5e4e50a5ae51b02f08f174eb"
})
but i want to know is there any other method??
Related
I have the following schema and I am trying to get posts, each containing an object indicating whether or not a user took a given action on a post.
// Post
const postSchema = new Schema(
{
title: { type: String, required: true },
body: { type: String, required: true },
},
)
// UserPostActions
const commentSchema = new Schema(
{
actionTaken: {
type: String,
enum: ['LIKE', 'FAVORITE', 'COMMENT'],
default: 'LIKE',
required: true
},
user: { type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true },
post: { type: mongoose.Schema.Types.ObjectId, ref: 'Post', required: true },
farm: { type: mongoose.Schema.Types.ObjectId, ref: 'Farm', required: true }
},
{ timestamps: true }
)
Given a userId, I want to get all posts. For each post, I want to know which of the 3 action types the user took on the post, so that the results look something like;
const results = [
{
_id: 1,
title: 'The title',
body: 'The body',
userActions: {
LIKE: true,
FAVORITE: false,
COMMENT: true
}
},
{
_id: 2,
title: 'The title',
body: 'The body',
userActions: {
LIKE: true,
FAVORITE: true,
COMMENT: true
}
},
{
_id: 3,
title: 'The title',
body: 'The body',
userActions: {
LIKE: false,
FAVORITE: false,
COMMENT: true
}
},
{
_id: 4,
title: 'The title',
body: 'The body',
userActions: {
LIKE: true,
FAVORITE: false,
COMMENT: false
}
}
]
So i try to aggregate the data from mongoDB using $match and $group to get the exact value an d format with data from mongoDB in JSON as Below:
[ {
_id: new ObjectId("6357b4237cf79bba3e66c096"),
userId: new ObjectId("635762fe85b94eac7466d965"),
formId: new ObjectId("6357921d49de88bb7fffcfe4"),
title: 'Quality',
username: 'Jansenstan24#gmail.coms',
date: '2022-10-25',
answer: {
'6357921d49de88bb7fffcfe8': 'john#nabatisnack.com',
Text: 'john#nabatisnack.com',
'6357b331235053a9d4e8d037': 'john#dose.com',
Email: 'john#dose.com',
'6357b335235053a9d4e8d03a': 'Maja',
Plant: 'Maja'
},
createdAt: 1666692131,
updatedAt: 1666692131,
__v: 0
},
{
_id: new ObjectId("6357b54922866fae378af370"),
userId: new ObjectId("635762fe85b94eac7466d965"),
formId: new ObjectId("6357921d49de88bb7fffcfe4"),
title: 'Quality',
username: 'Jansenstan24#gmail.coms',
date: '2022-10-25',
answer: {
'6357921d49de88bb7fffcfe8': 'john#dose.com',
Text: 'john#dose.com',
'6357b331235053a9d4e8d037': 'john#nabatisnack.com',
Email: 'john#nabatisnack.com',
'6357b335235053a9d4e8d03a': 'Cica',
Plant: 'Cica'
},
createdAt: 1666692425,
updatedAt: 1666692425,
__v: 0
},
{
_id: new ObjectId("6357b6a2a13ab3c4a462be8f"),
userId: new ObjectId("635647c1e24d0a4482e3c0a9"),
formId: new ObjectId("6357921d49de88bb7fffcfe4"),
title: 'Quality',
username: 'adam#wegodev.com',
date: '2022-10-25',
answer: {
'6357921d49de88bb7fffcfe8': '12',
Text: '12',
'6357b331235053a9d4e8d037': 'john#dose.coms',
Email: 'john#dose.coms',
'6357b335235053a9d4e8d03a': 'Ranca',
Plant: 'Ranca'
},
createdAt: 1666692770,
updatedAt: 1666692770,
__v: 0
}]
using this line of code in javascript:
forms = await Answer.aggregate([
{
$match: { title: "Quality" },
},
{ $group: { title: "Quality"} },
]);
what i expected is the result like this:
{
formId: new ObjectId("6357921d49de88bb7fffcfe4"),
title: 'Quality',
username: [{'Jansenstan24#gmail.coms',adam#wegodev.com}]
date: [{'2022-10-25','2022-10-26}]
answer: [{
'6357921d49de88bb7fffcfe8': 'john#nabatisnack.com',
Text: 'john#nabatisnack.com',
'6357b331235053a9d4e8d037': 'john#dose.com',
Email: 'john#dose.com',
'6357b335235053a9d4e8d03a': 'Maja',
Plant: 'Maja'
},{
'6357921d49de88bb7fffcfe8': 'john#dose.com',
Text: 'john#dose.com',
'6357b331235053a9d4e8d037': 'john#nabatisnack.com',
Email: 'john#nabatisnack.com',
'6357b335235053a9d4e8d03a': 'Cica',
Plant: 'Cica'
},...etc],
},
i try to use more complex query but it seems it not return the result i want and i've try to seek any related problem but it wont return the same result as i want
You have the right idea using $group, you just need to leverage it's syntax properly, like so:
db.collection.aggregate([
{
$match: {
title: "Quality"
}
},
{
$group: {
_id: "$title",
title: {
$first: "$title"
},
username: {
"$addToSet": "$username"
},
date: {
$addToSet: "$date"
},
formId: {
$addToSet: "$formId"
},
answer: {
$push: "$answer"
}
}
}
])
Mongo Playground
I'm trying to select especific fields from this document
{
_id: 60d9295db34f1c0144c9b8d4,
title: 'Este es el titulo',
slug: 'este-es-el-titulo',
date: '2021-06-27',
category: {
_id: 60d92921b34f1c0144c9b8d2,
title: 'Categoria 1',
slug: 'categoria-1',
id: '60d92921b34f1c0144c9b8d2'
},
cover: {
_id: 60d72c815e57e6015e38a4c7,
name: 'project4.png',
alternativeText: '',
caption: '',
hash: 'project4_3e8c906bdf',
ext: '.png',
mime: 'image/png',
size: 540.02,
width: 1895,
height: 883,
url: '/uploads/project4_3e8c906bdf.png',
formats: [Object],
provider: 'local',
related: [Array],
createdAt: 2021-06-26T13:32:49.389Z,
updatedAt: 2021-06-28T01:43:57.469Z,
__v: 0,
created_by: '60d69246c6f06d00f64312b0',
updated_by: '60d69246c6f06d00f64312b0',
id: '60d72c815e57e6015e38a4c7'
},
id: '60d9295db34f1c0144c9b8d4'
}
and I want get something like this:
{
_id: 60d9295db34f1c0144c9b8d4,
title: 'Este es el titulo',
slug: 'este-es-el-titulo',
date: '2021-06-27',
category: {
_id: 60d92921b34f1c0144c9b8d2,
title: 'Categoria 1',
slug: 'categoria-1',
id: '60d92921b34f1c0144c9b8d2'
},
cover: { url: '/uploads/project4_3e8c906bdf.png'}
id: '60d9295db34f1c0144c9b8d4'
}
I'm using Strapi with Mongodb and y was trying with the following code:
const requiredData = {
title: 1,
slug: 1,
date: 1,
category: 1,
cover: { url: 1 }
}
const populateData = [
{
path: 'category',
select: ['title', 'slug']
}
]
let editorsPick = await strapi.query('posts')
.model.find({ editorsPick: true}, requiredData)
.limit(3)
.populate(populateData)
But I only have this:
{
_id: 60d9295db34f1c0144c9b8d4,
title: 'Este es el titulo',
slug: 'este-es-el-titulo',
date: '2021-06-27',
category: {
_id: 60d92921b34f1c0144c9b8d2,
title: 'Categoria 1',
slug: 'categoria-1',
id: '60d92921b34f1c0144c9b8d2'
},
id: '60d9295db34f1c0144c9b8d4'
}
(Without cover image), and then try with:
let editorsPick = await strapi.query('posts')
.model.aggregate([
{"$match": { editorsPick: true}},
{"$project": requiredData}
])
But I got an empty array []
Please I need a little help, and sorry for my english
i make simple board app. but i face scrab problem.
i want to pull data in scrabContent when people unscrab. but it doesnt' work. help me plz..
My Schema looks like this. scrabContent means contents that i scrab. So, when i scrab some contents, they are stored in scrabContent.
const userSchema = new mongoose.Schema({
email: {
type: String,
unique: true,
required: true,
},
password: {
type: String,
required: true,
},
name: {
type: String,
required:true,
unique: true,
},
follower : [String],
following : [String],
boardBookmark: [],
scrabContent: [],
songs: [],
songsView: {
type: Number,
default :0,
},
profileImage: {
type: String,
}
});
this is schema data example.
{
follower: [],
following: [],
boardBookmark: [
{
name: 'asd',
introduction: 'dsadad',
boardId: '603a4e485d99d993e0bfdfee'
}
],
scrabContent: [
{
commentsNum: 3,
likes: [],
image: [Array],
isDeleted: false,
_id: 603b67e1904622ca9ee2cddb,
title: 'ㄴㅁㅇㄹㅁㄴㄹㅁ',
content: 'ㅁㅇㄴㄹㅁㄹㅁㄴㄹㅁㄴㄹ',
postUser: 'umpa',
postUserId: 603751786587acfbf1052d34,
boardId: 603a4e485d99d993e0bfdfee,
time: '2021/02/28 18:52:32',
__v: 0
},
{
commentsNum: 5,
likes: [Array],
image: [Array],
isDeleted: false,
_id: 603b09f509dcb8b594c1f015,
title: '테스트',
content: 'ㅋㅋ',
postUser: 'umpa',
postUserId: 603751786587acfbf1052d34,
boardId: 603a4e485d99d993e0bfdfee,
time: '2021/02/28 12:11:47',
__v: 0
}
],
songs: [
{
id: '1469319400',
type: 'songs',
href: '/v1/catalog/kr/songs/1469319400',
attributes: [Object],
name: 'LOVE AGAIN'
},
{
id: '1265893529',
type: 'songs',
href: '/v1/catalog/kr/songs/1265893529',
attributes: [Object],
name: 'Get You (feat. Kali Uchis)'
},
{
id: '1265893532',
type: 'songs',
href: '/v1/catalog/kr/songs/1265893532',
attributes: [Object],
name: 'Best Part (feat. H.E.R.)'
},
{
id: '1356070221',
type: 'songs',
href: '/v1/catalog/kr/songs/1356070221',
attributes: [Object],
name: 'Daniel'
},
{
id: '1438474485',
type: 'songs',
href: '/v1/catalog/kr/songs/1438474485',
attributes: [Object],
name: 'Falling'
}
],
songsView: 0,
_id: 603a84d9760444a652d2cc72,
email: 'test',
password: '$2b$10$w8b85O6KQwGIZ0D1x0TGle.qofoEC43OKI5cMSf7tfqld12fSUWlu',
name: 'test',
__v: 0
}
and this is server code to pull. req.user._id means User Schema's _id(in this case: 603a84d9760444a652d2cc72). and req.params.id means Content _id(in this case: 603b67e1904622ca9ee2cddb) in ScrabContent.
router.delete('/deleteScrabContent/:id', requireAuth, async (req, res) => {
try {
await User.findOneAndUpdate({_id: req.user._id}, {$pull: {scrabContent: {_id: req.params.id}}}, {new: true});
} catch (err) {
return res.status(422).send(err.message);
}
});
i don't know why scrabContent doesn't work.. help me T^T
I have seen this asked several times, but I haven't found a solution that has worked. I am trying to query a MongoDB using Mongoose .findById and am not getting the expected results. find({id: "..."}) is also not returning anything.
Using find without any parameters displays all of the expected results including id key-value pairs, but I cannot use the id value in the query.
Using mongoose: 5.4.9
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/mongo-exercises', { useNewUrlParser: true });
const courseSchema = new mongoose.Schema({
name: String,
author: String,
tags: [String],
date: { type: Date, default: Date.now },
isPublished: Boolean,
price: Number
});
const Course = mongoose.model('Course', courseSchema);
async function getCourses() {
return await Course
.find()
}
async function run() {
const result = await getCourses();
console.log(result);
}
run();
//Return
[ { tags: [ 'react', 'frontend' ],
_id: 5a68fdf95db93f6477053ddd,
date: 2018-01-24T21:43:21.589Z,
name: 'React Course',
author: 'Mosh',
isPublished: false,
__v: 0 },
{ tags: [ 'aspnet', 'backend' ],
_id: 5a68fde3f09ad7646ddec17e,
date: 2018-01-24T21:42:59.605Z,
name: 'ASP.NET MVC Course',
author: 'Mosh',
isPublished: true,
price: 15,
__v: 0 },
{ tags: [ 'node', 'backend' ],
_id: 5a68fe2142ae6a6482c4c9cb,
date: 2018-01-24T21:44:01.075Z,
name: 'Node.js Course by Jack',
author: 'Jack',
isPublished: true,
price: 12,
__v: 0 },
{ tags: [ 'node', 'backend' ],
_id: 5a68fdd7bee8ea64649c2777,
date: 2018-01-24T21:42:47.912Z,
name: 'Node.js Course',
author: 'Mosh',
isPublished: true,
price: 20,
__v: 0 },
{ tags: [ 'node', 'backend' ],
_id: 5a68ff090c553064a218a547,
date: 2018-01-24T21:47:53.128Z,
name: 'Node.js Course by Mary',
author: 'Mary',
isPublished: false,
price: 12,
__v: 0 },
{ tags: [ 'angular', 'frontend' ],
_id: 5a6900fff467be65019a9001,
date: 2018-01-24T21:56:15.353Z,
name: 'Angular Course',
author: 'Mosh',
isPublished: true,
price: 15,
__v: 0 },
{ tags: [ 'express', 'backend' ],
_id: 5a68fdc3615eda645bc6bdec,
date: 2018-01-24T21:42:27.388Z,
name: 'Express.js Course',
author: 'Mosh',
isPublished: true,
price: 10,
__v: 0 } ]
That code verifies I'm connected to the correct database and retrieving real ids. When I modify the getCourses function as shown below, I get null or an empty array depending on whether I use findById or find({id: "..."}).
async function getCourses() {
return await Course
.findById('5a68fdf95db93f6477053ddd')
}
//null
async function getCourses() {
return await Course
.find({ id: '5a68fdf95db93f6477053ddd' })
}
// []
async function getCourses() {
return await Course
.find({ _id: '5a68fdf95db93f6477053ddd' })
}
// []
Any help would be greatly appreciated. Thank you!
EDIT: Showing full find() response.
Upon our discussion as your importing the data from JSON file, So its inserting the _id as string, While finding the document by _id, moognoose automatically converting string to Object.
// Original JSON
{
"_id": "5a68fde3f09ad7646ddec17e",
"tags": [
"aspnet",
"backend"
],
"date": "2018-01-24T21:42:59.605Z",
"name": "ASP.NET MVC Course",
"author": "Mosh",
"isPublished": true,
"price": 15,
"__v": 0
}
Solution 1 :
To insert the _id as in the JSON, change your _id field with $oid as below,
{
"_id": { "$oid": "5a68fde3f09ad7646ddec17e" },
"tags": [
"aspnet",
"backend"
],
"date": "2018-01-24T21:42:59.605Z",
"name": "ASP.NET MVC Course",
"author": "Mosh",
"isPublished": true,
"price": 15,
"__v": 0
}
Solution 2 :
Remove _id from your JSON, MongoDB will generate a _id automatically
{
"tags": [
"aspnet",
"backend"
],
"date": "2018-01-24T21:42:59.605Z",
"name": "ASP.NET MVC Course",
"author": "Mosh",
"isPublished": true,
"price": 15,
"__v": 0
}