How to find from multiple values in mongodb - node.js

There is a collection in MongoDB like:
{
"_id" : ObjectId("5bcc4c7d1e2c701be024de99"),
"className" : "Class 10",
"gradeLevel" : "10th",
"subjectName" : "Math",
"teacherId" : "abcd#gmail.com",
"__v" : 0
},
{
"_id" : ObjectId("5bd45277f5b9430013f4a604"),
"className" : "Class 11",
"gradeLevel" : "11th",
"subjectName" : "Maths",
"teacherId" : "abcd#gmail.com",
"__v" : 0
},
{
"_id" : ObjectId("5bd470fe452cb33af4b8407a"),
"className" : "Class 10",
"gradeLevel" : "12th",
"subjectName" : "Math",
"teacherId" : "abcd#gmail.com",
"__v" : 0
},
Now I want to fetch those documents with values of_id:
ObjectId("5bd45277f5b9430013f4a604"), ObjectId("5bd470fe452cb33af4b8407a").
I am using mongoose and node.js. So please tell me is there any way to do this.

Model.find({ _id: { $in: ['5bd45277f5b9430013f4a604', '5bd470fe452cb33af4b8407a'] } })
.then(docs => console.log(docs))
.catch(err => console.log(err));

Related

NodeJS how to make a special get CRUD

I'm writing some nodeJS code in which I want to make a get request and the result of this get must respect two condition the first is that the imei.name is passed in parameeteres req.query.imei and the second condition is that the test filed is not empty that's my MongoDb database.
{
"_id" : ObjectId("5eb7f90fb88d8d4d94184333"),
"imei" : {
"name" : "bokhhjbr",
"modele" : "5486"
},
"__v" : 0
}
{
"_id" : ObjectId("5eb7fb9cb88d8d4d94184334"),
"imei" : {
"name" : "865566048694354",
"modele" : "CPH1803"
},
"__v" : 0
}
{
"_id" : ObjectId("5eba73395fd8dd073065efdf"),
"imei" : {
"name" : "bok55555555555hjbr",
"modele" : "5486"
},
"createdAt" : ISODate("2020-05-12T09:58:17.203Z"),
"updatedAt" : ISODate("2020-05-12T09:58:17.203Z"),
"__v" : 0
}
{
"_id" : ObjectId("5ed0f93c0c93ec1c785358ab"),
"imei" : {
"name" : "865566048694354"
},
"test" : {
"tactileState" : "1",
"pixelState" : "1",
"greyState" : "1"
},
"createdAt" : ISODate("2020-05-29T11:59:56.441Z"),
"updatedAt" : ISODate("2020-05-29T11:59:56.441Z"),
"__v" : 0
}
{
"_id" : ObjectId("5ed0f9420c93ec1c785358ac"),
"imei" : {
"name" : "865566048694354"
},
"test" : {
"tactileState" : "1",
"pixelState" : "1",
"greyState" : "1"
},
"createdAt" : ISODate("2020-05-29T12:00:02.040Z"),
"updatedAt" : ISODate("2020-05-29T12:00:02.040Z"),
"__v" : 0
}
I tried to write this method but without any result
router.get('/gettdata/', (req, res, next) => {
let aa=req.query.imei;
console.log(aa);
Post.findOne(
imei:{"imei.name":req.query.imei},
test: {$exists:true})
.then((posts) => {
res.json(posts);
console.log(posts);
})
.catch(err => console.log(err))
});

nodeJS mongoose how to make a special get crud

That's my mongodb data base shown in cmd as you see there is a field named test which exist a time and one other time didn't exist I want to write a get method to find field which contain only imei without test
router.get('/', (req, res, next) => {
Post.find()
.then((posts) => {
res.json(posts);
console.log(posts);
console.log("ok" + JSON.stringify(req.body) + req.body.imei);
})
.catch(err => console.log(err))
});
Here the get method it show me all data base I want to customize it.
{
"_id" : ObjectId("5eb6b927e1c2916320ab28de"),
"imei" : {
"name" : "50"
},
"test" : {
"batterieState" : "0"
},
"__v" : 0
}
{
"_id" : ObjectId("5eb6bbbc09183a3e4c833ebe"),
"imei" : {
"name" : "xx"
},
"__v" : 0
}
{
"_id" : ObjectId("5eb6bbcb09183a3e4c833ebf"),
"imei" : {
"name" : ""
},
"__v" : 0
}
{
"_id" : ObjectId("5eb6bc7809183a3e4c833ec0"),
"imei" : {
"name" : "865566048694354"
},
"__v" : 0
}
{
"_id" : ObjectId("5eb6bcc309183a3e4c833ec1"),
"imei" : {
"name" : "865566048694354"
},
"__v" : 0
}
{
"_id" : ObjectId("5eb6bd1209183a3e4c833ec2"),
"imei" : {
"name" : "865566048694354"
},
"__v" : 0
}
{
"_id" : ObjectId("5eb6bdc609183a3e4c833ec3"),
"imei" : {
"name" : "865566048694354"
},
"__v" : 0
}
{
"_id" : ObjectId("5eb6be4609183a3e4c833ec4"),
"imei" : {
"name" : "xx"
},
"test" : {
"tactileState" : "0",
"pixelState" : "0",
"greyState" : "0"
},
"__v" : 0
}
{
"_id" : ObjectId("5eb6be6609183a3e4c833ec5"),
"imei" : {
"name" : "865566048694354"
},
"__v" : 0
}
{
"_id" : ObjectId("5eb6beef09183a3e4c833ec6"),
"imei" : {
"name" : "xx"
},
"test" : {
"tactileState" : "0",
"pixelState" : "0",
"greyState" : "0"
},
"__v" : 0
}
{
"_id" : ObjectId("5eb6bf8709183a3e4c833ec7"),
"imei" : {
"name" : "865566048694354"
},
"test" : {
"tactileState" : "ignore",
"pixelState" : "ignore",
"greyState" : "ignore"
},
"__v" : 0
}
I want some help for this to write this method correctly to get only fields with imei only and without test.
Use this query
Post.find({
imei: {
$exists: true
},
test: {
$exists: false
}
})
Docs of $exists operator

Mongoose TypeScript Aggregation: does not exist on type 'any[]'

I'm trying to swap out a regular mongo call for an aggregate call. the original that was working is ..
const account = await userModel
.findOne({ 'shared.username': username })
.exec();
console.log(account._id)
The new aggregate function is...
const account = await userModel.aggregate([
{
$match: {
'shared.username': username,
},
},
{
$lookup: {
as: 'photos',
foreignField: 'userId',
from: 'photos',
localField: '_id',
},
},
]);
console.log(account._id)
// ^ Error
The error im getting is
Property '_id' does not exist on type 'any[]'.ts(2339)
im sure their is _id being returned as i can see it in Studio 3T aggregation output
{
"_id" : ObjectId("5e10983cb182628af48e590a"),
"shared" : {
"currency" : "USD",
"followers" : 0,
"following" : 0,
"language" : "en",
"loggedIn" : true,
"twofactor" : false,
"warningMessage" : "verify",
"email" : "email#gmail.com",
"fullName" : "James",
"username" : "57fe31142e10",
"location" : "/57fe31142e10"
},
"photos" : [
{
"_id" : ObjectId("5e117b8f227a32597cdcbb6e"),
"category" : "Double Deckers",
"previewId" : "5e10983cb182628af48e590a/0f5d0010a4e55794419c03328184cfb45984bf43.jpg",
"published" : true,
"thumbnailId" : "5e10983cb182628af48e590a/54265d07a962f8544a9ebdc1d876775d9eeed471.jpg",
"userId" : ObjectId("5e10983cb182628af48e590a"),
"zoomId" : "5e10983cb182628af48e590a/fe0b2016a0be2b26259aaf5152ef22edfffa0c57.jpg",
"createdAt" : ISODate("2020-01-05T06:00:47.756+0000"),
"updatedAt" : ISODate("2020-01-05T06:00:47.756+0000"),
"__v" : 0
},
{
"_id" : ObjectId("5e11ab2f0f451779f70f89b1"),
"category" : "Single Decker",
"previewId" : "5e10983cb182628af48e590a/30d496e44faae1345e4c555accfdc6446fd11945.jpg",
"published" : true,
"thumbnailId" : "5e10983cb182628af48e590a/9293dd5517f694341a2e582df670dc9bbaba0763.jpg",
"userId" : ObjectId("5e10983cb182628af48e590a"),
"zoomId" : "5e10983cb182628af48e590a/0a038434e857b05ef8aa46da6dab01259ba2b03e.jpg",
"createdAt" : ISODate("2020-01-05T09:23:59.007+0000"),
"updatedAt" : ISODate("2020-01-05T09:23:59.007+0000"),
"__v" : 0
},
{
"_id" : ObjectId("5e11aba00f451779f70f89b2"),
"category" : "Midi",
"previewId" : "5e10983cb182628af48e590a/2267d14aa642d6cee86319909177ce4eef45cbcc.jpg",
"published" : true,
"thumbnailId" : "5e10983cb182628af48e590a/9d006f1ed361540ecf9d24c807a111770cf9e44f.jpg",
"userId" : ObjectId("5e10983cb182628af48e590a"),
"zoomId" : "5e10983cb182628af48e590a/88a87440a9b7845aa44c72411edddc98ea56f6b9.jpg",
"createdAt" : ISODate("2020-01-05T09:25:52.019+0000"),
"updatedAt" : ISODate("2020-01-05T09:25:52.019+0000"),
"__v" : 0
}
]
}
The error is correct, aggregation output is an Array of objects.
You want to do: (assuming the aggregation returns results)
console.log(account[0]._id)

How to get total record by object id in nodejs

I want to get all category name and total record with respect to category object id.
I am new in Node JS and want to create api for listing and total record with respective object id.
My json for Categgory is -
/* 1 createdAt:8/21/2019, 3:00:35 PM*/
{
"_id" : ObjectId("5d5d0f3b3dff690eac4872ee"),
"isForHomePage" : false,
"isactive" : false,
"name" : "Welcome",
"description" : "Solutions for Your Business",
"catImage" : "http://localhost:3000/static/media/software-service.1ec2246b.jpg",
"createdTime" : 1566379835,
"__v" : 0
},
/* 2 createdAt:8/19/2019, 12:17:45 PM*/
{
"_id" : ObjectId("5d5a4611eb5bc029d4463406"),
"isForHomePage" : true,
"isactive" : false,
"name" : "Test",
"description" : "Solutions for Your Business",
"catImage" : "http://localhost:3000/static/media/software-service.1ec2246b.jpg",
"createdTime" : 1566197265,
"__v" : 0
},
/* 3 createdAt:8/19/2019, 12:10:01 PM*/
{
"_id" : ObjectId("5d5a44417d10952b50ff13a0"),
"isForHomePage" : true,
"isactive" : true,
"name" : "Software Services",
"description" : "Solutions for Your Business",
"catImage" : "http://localhost:3000/static/media/software-service.1ec2246b.jpg",
"createdTime" : 1566196801,
"__v" : 0
},
/* 4 createdAt:8/19/2019, 12:07:51 PM*/
{
"_id" : ObjectId("5d5a43bf7d10952b50ff139f"),
"isForHomePage" : true,
"isactive" : true,
"name" : "Analytics",
"description" : "Solutions for Your Business",
"catImage" : "http://localhost:3000/static/media/analytics.cf89d7fe.jpg",
"createdTime" : 1566196671,
"__v" : 0
}
and JSON for jobs is -
/* 1 createdAt:8/22/2019, 12:48:08 PM*/
{
"_id" : ObjectId("5d5e41b0807a2504e15dcc01"),
"status" : 8001,
"duration" : 10,
"isactive" : true,
"userWhoCreated" : ObjectId("5d5d40276ab29a4daef653ae"),
"companyNane" : "Sanganan It Solutions Pvt. Ltd.",
"contactPerson" : "Gaurav Sinha",
"jobTitle" : "iOS Developer",
"category" : ObjectId("5d5a4611eb5bc029d4463406"),
"description" : "iOS Developer lead requirement",
"descriptionLink" : "www.abc.com",
"createdTime" : 1566458288,
"__v" : 0
},
/* 2 createdAt:8/22/2019, 12:17:31 PM*/
{
"_id" : ObjectId("5d5e3a83979672041fee4d0a"),
"status" : 8002,
"duration" : 10,
"isactive" : true,
"userWhoCreated" : ObjectId("5d5d40276ab29a4daef653ae"),
"companyNane" : "Sanganan It Solutions Pvt. Ltd.",
"contactPerson" : "Gaurav Sinha",
"jobTitle" : "iOS Developer",
"category" : ObjectId("5d5a4611eb5bc029d4463406"),
"description" : "iOS Developer lead requirement",
"descriptionLink" : "www.abc.com",
"createdTime" : 1566456451,
"__v" : 0
}
We have category json and category object id is present in jobs json. Like Test category from Category JSON has two jobs in JOB JSON.
I have tried this solution -
router.get("/getAllCategory", function (req, res) {
categoryObj.find({ 'isactive': true }, function (err, CategoryList) {
if (err) {
var message = { "Success": 0, "Message": "Some error found" };
res.send(message)
}
else {
var message = { "Success": 1, "Category": CategoryList };
res.send(message)
}
})
});
but it is giving me list of categories not count.
my expected output json must be like this -
[
{
'categoryname': 'Analytics',
'totalJobsOfThisCategory':'0'
},
{
'categoryname': 'Software Services',
'totalJobsOfThisCategory':'0'
},
{
'categoryname': 'Test',
'totalJobsOfThisCategory':'2'
},
]
Use aggregate function of mongodb
db.jobs.aggregate([
{ $group: { _id: "$category", total: { $sum: 1 } } }
])
Use populate
const x= await X.find()
.populate('userWhoCreated', 'field1 field2')
.populate('category', 'field1 field2');
res.json({
x,
});

Mongodb find query for array

i'm trying - find query for array in mongodb,
db.users.find({posts:{$all:[_id : ObjectId("5cc83a158ceb346aa58b1161")]}})
db.users.find( { "posts.post" : {$all : []}})
//My MongoDB collections
> db.users.find().pretty()
{
"_id" : ObjectId("5cc83a158ceb346aa58b1161"),
"friends" : [ ],
"name" : "krishna soni",
"email" : "krishnasoni#gmail.com",
"password" : "krishna",
"posts" : [
{
"_id" : ObjectId("5cc8478118195b71e2ccd517"),
"post" : "hey users",
"createdTime" : ISODate("2019-04-30T13:02:57.621Z")
},
{
"_id" : ObjectId("5cc853ec0a5fde0e431898f3"),
"post" : "hey friends it's my final post",
"createdTime" : ISODate("2019-04-30T13:55:56.119Z")
}
],
"__v" : 0
}
//expected results is following
//display given objectId's posts array
"posts" : [
{
"_id" : ObjectId("5cc8478118195b71e2ccd517"),
"post" : "hey users",
"createdTime" : ISODate("2019-04-30T13:02:57.621Z")
},
{
"_id" : ObjectId("5cc853ec0a5fde0e431898f3"),
"post" : "hey friends it's my final post",
"createdTime" : ISODate("2019-04-30T13:55:56.119Z")
}
],
You just need to pass {posts:1}
Try this:
db.users.find({"_id" : ObjectId("5cc83a158ceb346aa58b1161")},{posts:1});

Resources