Node Output from mongo db as a list of objects - node.js

{
"dependencies" : [
{
"name" : "async",
"version" : "2.6.1"
},
{
"name" : "body-parser#1.18.3",
"version" : "1.18.3"
},
{
"name" : "cookie-parser#~1.4.3",
"version" : "1.4.3"
},
{
"name" : "debug#~2.6.9",
"version" : "2.6.9"
},
{
"name" : "express#~4.16.0",
"version" : "4.16.4"
},
{
"name" : "http-errors#~1.6.2",
"version" : "1.6.3"
},
{
"name" : "mongoose",
"version" : "5.3.13"
},
{
"name" : "morgan#~1.9.0",
"version" : "1.9.1"
},
{
"name" : "pug#2.0.0-beta11",
"version" : "2.0.0-beta11"
}
]
}
MongoDB Connected
[ { dependencies:
[ [Object],
[Object],
[Object],
[Object],
[Object],
[Object],
[Object],
[Object],
[Object] ] } ]
exports.repo_search = function(req, res, next) {
Repo.findById(req.params.id).populate('repo').exec(function(err, repo) {
if (err) {
return next(err);
}
if (repo == null) {
// No results.
var err = new Error('Repo copy not found');
err.status = 404;
return next(err);
}
Dependencies.find({ Repo_id: '2' }, { dependencies: 1, _id: 0 }).exec(function(err, list_dependencies) {
if (err) {
return next(err);
}
console.log(list_dependencies);
// Successful, so render.
//res.render('dependencies_list', { title: 'Dependencies List', list_dependencies: list_dependencies });
// Successful, so render.
res.render('repo_info_detail', {
title : 'Repo Detail',
repo : repo,
list_dependencies : list_dependencies
// repo_dependencies: results.repo_search
});
// console.log(Repo._id);
});
});
};
Hi, I am using Node and Mongodb with mongoose. I am trying to output a list of dependencies. When i do a console log i get a dependencies list of objects that are called object. The command i am using outputs on the mongo cmd line but when i try to query it in node , and put a console log in my controller i get this. Anybody Know how to fix it ? Thanks in advance.

that's not contain problems with your code.
Try with
console.log(list_dependencies[0]);
If not work, just change from string to object like this
const result = JSON.parse(list_dependencies);
console.log(result)

MongoDB "find" query returns an array(list) of results.(you see a list of objects)
If you are are expecting only one result better use "findOne" query.

Related

Unable to update mongodb document with nested object property from node api

I have the following mongodb document:
{
"_id" : ObjectId("5ee95b41ca023a3deb252ef2"),
"uid" : "jdoe",
"name" : "John Doe",
"employee_hire_date" : "2012-06-20",
"three_month_review_target" : "2012-09-20",
"six_month_review_target" : "2012-12-20",
"three_month_review_status" : {
"is_scheduled" : null,
"is_team_member_emailed" : null,
"is_review_executed" : null,
},
"six_month_review_status" : {
"is_scheduled" : null,
"is_team_member_emailed" : null,
"is_review_executed" : null,
}
}
I would like to update the three_month_review_status.is_scheduled nested property to true. I am using a put request to accomplish this:
const mongoose = require('mongoose');
const Reviews = require('../modules/reviews/models/reviews');
module.exports = (app) => {
app.put('/api/reviews/isScheduled', async (req, res) => {
console.log('body', req.body)
console.log('uid', req.body.uid)
console.log('is_scheduled', req.body.three_month_review_status.is_scheduled)
Reviews.findOneAndUpdate( { 'uid': req.body.uid }, { $set: { 'three_month_review_status.is_scheduled': req.body.is_scheduled }}, (err, result) => {
if (err) {
console.log('error', err)
}
else {
console.log('updated', result);
res.status(200).send(result);
}
} )
});
}
To test this, I execute this PUT request through Postman with the following request body:
{
"uid": "jdoe",
"three_month_review_status": {
"is_scheduled": "true"
}
}
However, when the request gets executed, the other two nested objects are removed and is_scheduled remains null. This is the document after the request is executed:
{
"_id" : ObjectId("5ee95b41ca023a3deb252ef2"),
"uid" : "jdoe",
"name" : "John Doe",
"employee_hire_date" : "2012-06-20",
"three_month_review_target" : "2012-09-20",
"six_month_review_target" : "2012-12-20",
"three_month_review_status" : {
"is_scheduled" : null
},
"six_month_review_status" : {
"is_scheduled" : null,
"is_team_member_emailed" : null,
"is_review_executed" : null,
}
}
What am I doing wrong? Here is my reviewsSchema for more context:
const { Schema, model } = require('mongoose');
const reviewsSchema = new Schema({
uid: String,
name: String,
employee_hire_date: String,
three_month_review_target: String,
six_month_review_target: String,
three_month_review_status: {
is_scheduled: Boolean,
is_team_member_emailed: Boolean,
is_review_executed: Boolean,
},
six_month_review_status: {
is_scheduled: Boolean,
is_team_member_emailed: Boolean,
is_review_executed: Boolean,
},
})
const Reviews = model('review', reviewsSchema);
module.exports = Reviews;
In Mongoose you don't need to specify the $set. Also based on the sample JSON that you send from the postman instead of req.body.is_scheduled you need to provide req.body.three_month_review_status.is_scheduled in the query. Also, need to add {new: true} if you want the findOneAndUpdate to return the updated document
So you can update the query like
Reviews.findOneAndUpdate(
{ uid: req.body.uid },
{
"three_month_review_status.is_scheduled":
req.body.three_month_review_status.is_scheduled,
},
{ new: true },
(err, result) => {
if (err) {
console.log("error", err);
} else {
console.log("updated", result);
res.status(200).send(result);
}
}
);

Finding max field value in mongodb using node

I am new in mongodb and node. I am trying to find the max value for a field (userId). But it returns nothing.
My code is
EventSchema.static("createUser",function(event,user,callback){
var That = this;
var max_usr_Id = '';
async.waterfall([
function(callback) {
That.find({"userId" : {"$ne" : ""}, "$and" : [{"userId" : {"$exists" : 1}}]}).sort({"_id" : -1}).limit(1).select("userId").exec(function(err, doc)
{
if(err)
{
console.log('User ID ERROR-');
callback({error:err,message:"Error getting max User ID"});
}else {
console.log('User ID-');
console.log(doc.userId);
max_usr_Id = doc.userId;
console.log(max_usr_Id);
}
});
console.log(max_usr_Id);
},
});
For some reason the control doesn't go inside the find function. When I try the following query in mongodb shell it works.
db.users.find({
"userId" : {
"$ne" : ""
},
"$and" : [
{
"userId" : {
"$exists" : true
}
}
]
}).sort({
"_id" : -1.0
}).limit(1);
Any help is highly appreciated. Thanks in advance.
The $and is not used in the proper way, try with:
That.find({ $and: [
{ "userId": { $ne: "" } },
{ "userId": { $exists: true } }
] }).sort( ...
Take a look at the $and documentation.
Edit
After seen the comments, the problem must be in the way the logging is made. You need to call toArray to get a collection, and then iterate over it (with forEach for instance):
...find( ... ).toArray(function(err, docs) {
// Print each document returned
docs.forEach(function(doc) {
console.log(doc.userId);
});
});

MongoDB $orderby not working with monk

After following the documentation to the letter, I can not get $orderby to work in NodeJS.
Here is my route in NodeJS:
// gets all the reviews about an instructor
app.get('/findInstructorReviews/:instructorID', function(req, res) {
var commentCollection = req.db.get('comments');
commentCollection.findOne(
{ _id: ObjectID(req.params.instructorID) },
{
$orderby: { 'comments.startDateTime' : -1 }
},
function(err, instructorReviews){debug(err);
if(err) return res.send({ status: 500, data: 'There was an error retreiving the instructor\'s reviews. Please try again later.' });
if(!instructorReviews) return res.send({ status: 404, data: 'This instructor does not have any review yet.' });
return res.send({ status: 200, data: instructorReviews.comments });
});
});
Here is the comments collection in my DB:
> db.comments.find().pretty()
{
"_id" : ObjectId("58d027f003232ca34e43d734"),
"comments" : [
{
"eventID" : ObjectId("58d2cd4e2f77b34b73dd8a04"),
"eventName" : "Yoga in the Park",
"startDateTime" : ISODate("2017-03-22T19:20:00Z"),
"comments" : [
"I really enjoyed his Yoga class.",
"He really helped me stretch out!",
"He taught me doggy style ;)"
]
},
{
"eventID" : ObjectId("58d2cd752f77b34b73dd8a05"),
"eventName" : "Spanish Lessons",
"startDateTime" : ISODate("2017-03-22T19:20:00Z"),
"comments" : [
"Learned a lot!",
"La biblioteca es manana!"
]
},
{
"eventID" : ObjectId("58d4130d5e18cdc928d0b82a"),
"eventName" : "Basketball Practice",
"startDateTime" : ISODate("2017-03-23T18:30:00Z"),
"comments" : [
"great guy! helped me improve my shooting game!",
"really knowledgeable about basketball!",
"excellent coach"
]
}
]
}
The one document in the comments collection is being returned to NodeJS, but not sorted by startDateTime like I want it to. It is being returned in the order it's already in - which would be Yoga, Spanish, Basketball. I've also tried sorting by 1 instead of -1, but that did not change the results.
Can anyone tell me what I am doing wrong?
Edit: I am using monk v1.0.1

mongodb deep update - mongoose .id() causing performance issue

mongoose level collection schema
{
sublevel: [{
"deeplevel": [{
}],
"deeplevel2": [{
}],
}]
}
//routes.js
dlDoc = { "dl1": "dl1" };
db.levels.update({ _id: ObjectId(levelId), "sublevel._id": ObjectId(sublevelId) }, { $push: { "sublevel.$.deeplevel1": dlDoc } }, function (err, updatedDoc) {
if (updatedDoc) {
res.json({ "status": 1 });
res.end();
//calling external apis to update more
result = externalApiResult();
db.levels.findById(level._id, 'sublevel._id sublevel.deeplevel1', function (err, levelFound) {
levelFound.sublevel.id(sublevelId).deeplevel.id(dlDoc._id)['result'] = result;
levelFound.save(function (err, savedDoc) {
});
})
}
});
I need to create and update the level collection's deeplevel1. in my case, the deeplevel1 will be inserted more than 2000 sub docs per day. when i want to update using mongoose .id(deepLevelId) function it is causing me performance issues in the server. is there any way to find the position of deeplevel document inserted once i update the level collection?. so that i can use the position in the update query. And please tell me a best way to update my deeplevel subdocuments without causing performance issues and works fast. thanks in advance.
db.collection.findOne() will be like this.
{
"_id" : ObjectId("563b35d1f07cc9d80a26436b"),
"name":"name",
sublevel:[{
"_id" : ObjectId("569bede3c717b670097519c7"),
"name" : "name",
"deeplevel2" : [{
"_id" : ObjectId("569c559329cc880c18989349"),
"logTime" : new Date("1/18/2016 03:30:48"),
"areaId" : ObjectId("568a6129de552e7dba98d547"),
}, {
"_id" : ObjectId("569c561929cc880c18989354"),
"logTime" : new Date("1/18/2016 03:30:48"),
"areaId" : ObjectId("568a6129de552e7dba98d547"),
}, {
"_id" : ObjectId("569c5945626ffb680e4512e9"),
"logTime" : new Date("1/18/2016 03:30:48"),
"areaId" : ObjectId("568a6129de552e7dba98d547"),
}, {
"_id" : ObjectId("569c594d626ffb680e4512eb"),
"logTime" : new Date("1/18/2016 03:30:48"),
"areaId" : ObjectId("568a6129de552e7dba98d547"),
}
]
}]
}

Unable to use result of aggregation with pipeline

I am using aggregation for get the data I need.
app.post('/test3', function(request,response){
var pipeline = [{$unwind:"$inventar"}
,{$match:{"tablename":tablename,"inventar.isstammkost":true,"inventar.accepted":"1"}}
,{$project : { "inventar" : 1}}
,{$group : {_id : null, Inventar : { $push:"$inventar"}}}]
Move.aggregate(pipeline, function(err, res) {
//var InvObj = res2.toObject();
console.log(res);
response.json(res);
});
});
I don't understand the result of the aggregation:
The console.log(res) gives
[ { _id: null, Inventar: [ [Object], [Object] ] } ]
and response.json(res) gives
[1]
0: {
_id: null
Inventar: [2]
0: {
accepted: "1"
ean: "802.6784.232"
isstammkost: true
stammkost: "IWXI"
}-
1: {
accepted: "1"
ean: "802.2000.100"
isstammkost: true
stammkost: "IWXI"
}
}
Why I can't make a JavascriptObject with var Obj = res.toObject();?
I get undefined if I try it.
I need to acces the array "Inventar" in the object.

Resources