Mongoose findOne by reference returns null - node.js

I have some events in the event collection and some users in the users collection.
I have a mapping of events and users in another collection. The event_id field in that collection is a reference to the event collection(ObjectId). But when I search schema using the following command I get null as a response
db.eventusers.findOne({event_id :'57988cd30e9811750324c080'})
returns null
on the other hand when i search using user field which is not a reference, just a string containing user id, I get the result as follows.
db.eventusers.findOne({user_id :"578cdcdd56eaec041b6caf3e"})
{
"_id" : ObjectId("57988d190e9811750324c081"),
"created_at" : "1469615385595",
"updated_at" : "1469615618502",
"user_id" : "578cdcdd56eaec041b6caf3e",
"event_id" : ObjectId("57988cd30e9811750324c080"),
"deleted" : false,
"invited" : false,
"host" : true,
"status" : -1,
"__v" : 0
}

I have found out the solution. If the field was defined in Mongoose Schema as Schema.Types.ObjectId then in the Query id should be ObjectId rather than String. So instead of query {event_id :'57988cd30e9811750324c080'} it should be {event_id :ObjectId('57988cd30e9811750324c080')}:
db.eventusers.findOne({event_id :ObjectId('57988cd30e9811750324c080')})
{
"_id" : ObjectId("57988d190e9811750324c081"),
"created_at" : "1469615385595",
"updated_at" : "1469615618502",
"user_id" : "578cdcdd56eaec041b6caf3e",
"event_id" : ObjectId("57988cd30e9811750324c080"),
"deleted" : false,
"invited" : false,
"host" : true,
"status" : -1,
"__v" : 0
}

Related

how to get the another collection data whose id is stored in array

I am having a collection like this whose users ids are stored inside the array,I need to query the collection A to get collection B whose "_id" (only "_id") is stored in array type , how to get in mongodb using aggregate ?
collection A :
{
"_id" : ObjectId("5ccfc2d176013e48a4ec0eed"),
"position" : ObjectId("5c73bcd0697b545c329a4bd4"),
"users" : [
"5bbf3cc7381e7a6530872089"
],
"inCase" : [],
"completed" : false,
}
am having second collection as
Collection B
{
"_id" : ObjectId("5b517a2bebb3b14b4cd78ca9"),
"firstName" : "Katie",
"lastName" : "Carter",
"languages" : [
"English",
"",
""
],
}
My code
{$lookup:{from:'user',localField:'users',foreignField:'_id',as:'users'}},
{$unwind:'$users'},
let me know how to resolve it?

How to add/update in array document with condition in mongoose

I need to perform the upsert operation. Below is my document structure.
I want to update the spin_details array when there is a match found with package_id but with two conditions i.e. user_id & spin_details.package_id.
If there is a match with user_id but there is no match with spin_details.package_id then some package information has to be pushed into the spin_details array. If there is no match with user_id(only) itself then it should be able to insert a new document.
{
"_id" : ObjectId("6234ffa6bd36b0e5a05ac913"),
"user_id" : ObjectId("6230e5e2b1530b407cedeb1d"),
"__v" : 0,
"is_active" : true,
"spin_details" : [
{
"package_id" : ObjectId("6230e5e2b1530b407cedeb9d"),
"spin_count" : 10,
"_id" : ObjectId("6234ffa6f390e1fafa8e215b")
},
{
"package_id" : ObjectId("6230e5e2b1530b407cedeb2a"),
"spin_count" : 25,
"_id" : ObjectId("6234ffa6f390e1fafa8e409b")
}
]
}
I can do this using multiple different queries and then based on the result value. How can I do this with a single mongoose query for this situation?

Query an array in MongoDB

I have this collection in MongoDB:
{
"_id" : ObjectId("5df013b10a88910018267a89"),
"StockNo" : "33598",
"Description" : "some description",
"detections" : [
{
"lastDetectedOn" : ISODate("2020-01-29T04:36:41.191+0000"),
"lastDetectedBy" : "comp-t",
"_id" : ObjectId("5e3135f68c9e930017de8aec")
},
{
"lastDetectedOn" : ISODate("2019-12-21T18:12:06.571+0000"),
"lastDetectedBy" : "comp-n",
"_id" : ObjectId("5e3135f68c9e930017de8ae9")
},
{
"lastDetectedOn" : ISODate("2020-01-29T07:36:06.910+0000"),
"lastDetectedBy" : "comp-a",
"_id" : ObjectId("5e3135f68c9e930017de8ae7")
}
],
"createdAt" : ISODate("2019-12-10T21:52:49.788+0000"),
"updatedAt" : ISODate("2020-01-29T07:36:22.950+0000"),
"__v" : NumberInt(0)
}
I want to search by StockNo and get the name of the computer that last detected it (lastDetectedBy) only if lastDetectedOn was in the last 5 minutes with Mongoose in node.js with Express.
I also have this collection:
{
"_id" : ObjectId("5df113b10d35670018267a89"),
"InvoiceNo" : "1",
"InvoiceDate" : ISODate("2020-01-14T02:18:11.196+0000"),
"InvoiceContact : "",
"isActive" : true
},
{
"_id" : ObjectId("5df013c90a88910018267a8a"),
"InvoiceNo" : "2",
"InvoiceDate" : ISODate("2020-01-14T02:18:44.279+0000"),
"InvoiceContact : "Bob Smith",
"isActive" : true
},
{
"_id" : ObjectId("5e3096bb8c9e930017dc6e20"),
"InvoiceNo" : "3",
"InvoiceDate" : ISODate("2020-01-14T02:19:50.155+0000"),
"InvoiceContact : "",
"isActive" : true
}
And I want to update all the documents with empty InvoiceContact which has been issued in the last 30 seconds (or any date range between now and sometime in the past) with isActive equals true to isActive equals false. So for example, the first record has been issued in the last 30 seconds without InvoiceContact and isActive is true so this must be updated but the next two records will remain untouched for different reasons, the second record has InvoiceContact and the third record is out of range.
First Part
var mins5 = new Date(ISODate() - 1000* 60 * 5 )
db.getCollection('user').find({$and:[
{ "StockNo":"33598"},
{"detections.lastDetectedOn" : { $gte : mins5 }}
]})
.map(function(list){
var results = [];
list.detections.forEach(function (detections){
if(detections.lastDetectedOn > mins5){
results.push(detections.lastDetectedBy);
}
})
return results;
});
Second Part could be solved by a similar query using update instead of find.

get count of multiple values of an array in mongodb

I want to perform a search in mongodb and nodejs which will return the count of ids that I will provide.
my collection is a log table
{
"_id" : ObjectId("5836d0f7f8462cbc6d0caffc"),
"DeviceId" : "abcd1234",
"AppType" : "web",
"UserId" : "5836cb01f8462cbc6d0caff8",
"ArticleId" : "5836cb01f8462cbc6d0caff8",
"Timestamp" : ISODate("2016-11-24T11:37:27.851Z")
},
{
"_id" : ObjectId("5836dba8a2943528448a3050"),
"DeviceId" : null,
"AppType" : null,
"UserId" : null,
"ArticleId" : 5836e493f2acbd1d34648e78,
"Timestamp" : ISODate("2016-11-24T12:23:04.484Z")
},
{
"_id" : ObjectId("5836e445c3b43429b4810ad4"),
"DeviceId" : null,
"AppType" : null,
"UserId" : null,
"ArticleId" : 5836d0f7f8462cbc6d0caffc,
"Timestamp" : ISODate("2016-11-24T12:59:49.820Z")
},
{
"_id" : ObjectId("5836e493f2acbd1d34648e78"),
"DeviceId" : null,
"AppType" : null,
"UserId" : null,
"ArticleId" : 5836d0f7f8462cbc6d0caffc,
"Timestamp" : ISODate("2016-11-24T13:01:07.030Z")
}
and so on...
my search string will be, search need to be performed on ArticleId
{"5836d0f7f8462cbc6d0caffc",
"5836e493f2acbd1d34648e78",
"5836dba8a2943528448a3050"}
and I want a result set like below
{
"1":{ArticleId:"5836d0f7f8462cbc6d0caffc", count:2},
"2":[ArticleId:"5836e493f2acbd1d34648e78", count:9},
"3":[ArticleId:"5836dba8a2943528448a3050", count:35}
}
Can any one please provide me the query, thanks in advance
I don't know if you realize, but all of your counts will be 1.
That's because every _id in Mongo is unique so if it's there then it's there only once.
Also, the output that you want is invalid:
{ 1:{_id:ObjectId("5836d0f7f8462cbc6d0caffc"), count:2},
2:{ObjectId("5836e493f2acbd1d34648e78"), count:9},
3:{ObjectId("5836dba8a2943528448a3050"), count:35}}
It's not valid JSON, not valid JavaScript, not valid Hjson, not valid JSON5, not valid anything - so you will never be able to get that result no matter what you do. (And also, if you change the expected output, every count will still be 1 so fixing the format is pointless anyway.)

how to query a collection based on value of a field array in mongoose

I have the following user schema
{
"__v" : 26,
"_id" : ObjectId("52b47058fe5e3493a2cf8365"),
"live_sockets" : [
"CEGok0rSz2UtBIHX9DlV",
"s6M45OA0MDBs4aGL9DlW",
"2XiszSuyiPAGr-Ga9ZCN",
"lIFNEeUgXRB6tgvP9ZCO",
"JPtzQOD_52maf6VS9gtb",
"kDL06aXiI8WWlig19gtc",
"75Bt5p6WqgmRcyer9xSm",
"Ge_sKLen32Q91wLW9xSn",
"EpHt3qju34GTZevU_Bsd",
"n0hq0EQAjJOptxdy_qEB",
],
"name" : {
"first" : "Test",
"last" : "User"
},
"notifications_count" : 0,
"role" : 1
}
How can i query a user based on a particular live socket as socket_ids are unique.
If i have a variable called current_socket_id how can i find a user which the socket belongs to..?
db.collection.find({"live_sockets" : {$in : [socketId]}},{"name" : 1,"_id":0})
Will give the name for the socket id

Resources