Basically i want to insert into my Mongodb collection called "Events" an array of objects called "Events" with an id for each entry into the array.
This is the result i want to get in json:
{
"events" : [
{
"_id" : ObjectId("53a99cc608ad49712a830081"),
"eTitle" : "Freshers Fair",
"eDesc" : "Bring some friends with you oh wait, you have non ha !",
"eDate" : "2014-06-19 11:20",
"eLink" : "http://fair.com",
"eEvent" : "NEFS"
},
{
"_id" : ObjectId("53a99cc608ad49712a830082"),
"eTitle" : "Blahh",
"eDesc" : "Blah fdinidf !",
"eDate" : "2014-06-19 11:20",
"eLink" : "http://google.com",
"eEvent" : "NEFS"
}
]
}
So far this is the result i have:
[
{
"_id":"53a9b5ed745363432d823d7a",
"eTitle":"jrnfdeiujn rd",
"eDesc":"grfdsreds",
"eDate":"2014-07-05 22:33",
"eLink":"reser",
"eEvent":"Victoria Center"
},
{
"_id":"53a9b771745363432d823d7b",
"eTitle":"Hello worlds",
"eDesc":"blah",
"eDate":"2014-07-20 22:33",
"eLink":"http://google.com",
"eEvent":"social"
}
]
This is how i insert data with node.js:
// Set our collection
var collection = db.get('Events');
// Submit to the DB
collection.insert({
"eTitle" : eTitle,
"eDesc" : eDesc,
"eDate" : eDate,
"eLink" : eLink,
"eEvent" : eEvent
}, function (err, doc) {
if (err) {
// If it failed, return error
res.send("There was a problem adding the information to the database.");
}
else {
// If it worked, set the header so the address bar doesn't still say /adduser
res.location("eventlist");
// And forward to success page
res.redirect("eventlist");
}
});
So please i how do i make the format look this the first json format i provided. sorry for the nooby question, just started learning node ! Thanks alot
UPDATE
To post Events:
router.get('/eventlist', function(req, res) {
var db = req.db;
var collection = db.get('Events');
collection.find({},{},function(e,docs){
console.log(docs);
res.send(docs);
// res.render('eventlist', {docs: JSON.stringify(docs), title: 'Test'});
});
});
You can do this:
collection.find({},{},function(e,docs){
var doc = { Events : docs };
console.log(doc);
res.send(doc);
// res.render('eventlist', {docs: JSON.stringify(docs), title: 'Test'});
});
Related
I've been stressing around trying to fix this and I've burnt myself out. I'm calling my serverless mysql trying to get kanbans from teams. I've used this method multiple times and all were working fine but that is most likely because of they only return single item whilst this returns multiple items.
This is my code which returns empty object.
async function getKanbans(team_id){
let kanbans = [];
await sql_query(`SELECT id, sName FROM table WHERE iTeam = ?`, [team_id])
.then(result => {
result.forEach(kanban => {
// console.log(kanban);
kanbans.push({
id: kanban.id,
name: kanban.sName
});
});
})
.catch(err => {
console.log(err);
});
console.log(kanbans);
return kanbans;
}
As you can see.. I am trying to print kanbans and I do get:
[
{ id: 1, name: 'Kanban_1' },
{ id: 2, name: 'Kanban_2' }
]
of out it. Then I'm trying to return it to the item that called this function and this is how that looks like:
teams.push({
id : team.id,
sName : team.sName,
sColor : team.sColor,
aKanbans : result[0]['selectedTeam'] == team.id ? getKanbans(team.id) : null,
});
(a small snippet of something bigger)
Okay, so now when I try and look at the data response (from the frontend) I get this:
{
"success": true,
"message": "Found teams",
"teams": [
{
"id": 1,
"sName": "Team1",
"sColor": "#fcba03",
"aKanbans": {}
},
{
"id": 2,
"sName": "Team2",
"sColor": "#2200ff",
"aKanbans": null
}
]
}
aKanbans from Team1 is empty, empty object. What the **** do I do? I tried mapping it and still got an empty object. React/javascript is not my main language, I just like to learn. Any suggestions?
You are mixing async / await function with normal Promises handling.
Try to change your getKanbans code like this:
async function getKanbans(team_id) {
let kanbans = [];
try {
const result = await sql_query(
`SELECT id, sName FROM table WHERE iTeam = ?`,
[team_id]
);
result.forEach((kanban) => {
kanbans.push({
id: kanban.id,
name: kanban.sName,
});
});
} catch (err) {
console.log(err);
}
return kanbans;
}
And then populate the teams using (declare the parent async):
teams.push({
id : team.id,
sName : team.sName,
sColor : team.sColor,
aKanbans : result[0]['selectedTeam'] == team.id ? getKanbans(team.id) : null,
});
I'm creating a restful API for blog application.
I have to update an attribute of a blog using postman. The object in the database of which an attribute has to be updated looks something like this:
{
"_id": "5a5306a9432f7b12f6e77a21",
"title": "new article",
"_author": {
"username": "linuxuser"
},
"content": "content of the article goes here",
"__v": 0,
"createdAt": "2018-01-08T05:48:41.683Z"
}
I may have to update any attribute but I cannot address it in code dynamically.
Here's the code:
put('/updateblog', function(req, res) {
db.blogModel.findById(req.query.id, function(err, blog) {
if (err) {
res.send(err);
}
blog.title = req.body.title;
// here instead to title i have to update the attribute which is passed through body parameter
blog.save(function(err) {
if (err) {
res.send(err);
}
res.json({
message: "blog updated"
});
});
});
});`
here instead of updating title, I want to update an attribute which is passed through body parameter. I do not know what client is going to send, so, I'm looking for more generic code.
For instance, a user sent a put request to update content attribute, then how do I write code so that corresponding attribute is updated rather than the title like in the above code.
you can get the keys from req.body and iterate or if req.body will contain only the user updated key & value of existing fields in your collection, you can directly use that as update object, but prefer to use some path like req.body.userUpdate for user's updates.
var updateObject = {};
for ( var key in req.body ) { //add logic to filter non existing fields
updateObject[key] = req.body[key] //change path if required
}
once update object has been created use findByIdAndUpdate to update
findByIdAndUpdate(req.query.id, {$set : updateObject } , function(err, blog ) {...}
in mongo CLI
> db.x.find().pretty()
{
"_id" : "5a5306a9432f7b12f6e77a21",
"title" : "new article",
"_author" : {
"username" : "linuxuser"
},
"content" : "content of the article goes here",
"__v" : 0,
"createdAt" : "2018-01-08T05:48:41.683Z"
}
update object
> var mod = {}
> mod['content']='new content'
new content
update
> db.x.update({"_id": "5a5306a9432f7b12f6e77a21"}, {$set : mod}, {$upsert:false})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
output
> db.x.find().pretty()
{
"_id" : "5a5306a9432f7b12f6e77a21",
"title" : "new article",
"_author" : {
"username" : "linuxuser"
},
"content" : "new content",
"__v" : 0,
"createdAt" : "2018-01-08T05:48:41.683Z"
}
>
Schema and model:
var schema = new mongoose.Schema({
timestamp_hour: Date,
deviceID: Number,
minutes: {
'0': {temperature: Number},
'1': {temperature: Number},
.
.
.
'59': {temperature: Number}
}
},{
collection: 'devices'
});
var model = mongoose.model('deviceData', schema);
Now in a POST request, I receive some data from an external source containing a timestamp, deviceID and temperature value.
My primary key is timestamp_hour and deviceID, so if there is an existing document in the database, I need to store the temperature value in minutes: {[minute_value]: temperature}. I currently derive minute_value from the timestamp, and I can query the database, all well and good. Now I need to update the minutes object in the document by adding the new key-value pair.
So after deriving the required values, I try running this:
var query = {timestamp_hour: timestamp, deviceID: deviceID};
var update = {minutes: {[minute]: {temperature: tempData}}};
deviceData.findOneAndUpdate(query, update, {upsert: true}, function(err, doc){
if(err) return res.send(500, {error: err});
return res.send("successfully saved");
});
Now the issue is, it replaces the entire minutes object inside document with the new single value.
Example:
Original document:
{
"deviceID" : 1,
"timestamp_hour" : ISODate("2016-10-29T08:00:00Z"),
"minutes" : { "38" : { "temperature" : 39.5 } },
}
Document after update:
{
"deviceID" : 1,
"timestamp_hour" : ISODate("2016-10-29T08:00:00Z"),
"minutes" : { "39" : { "temperature" : 38.0 } },
}
What I need:
{
"deviceID" : 1,
"timestamp_hour" : ISODate("2016-10-29T08:00:00Z"),
"minutes" : { "38" : { "temperature" : 39.5 }
"39" " { "temperature" : 38.0 } },
}
I'm new to MEAN, but I can see why my approach doesn't work since the update call just modifies the nested object.
I'd appreciate any help regarding the correct approach to use for achieving this functionality.
You can do this within a single update using a combination of the dot and bracket notations to construct the update object as follows:
var query = { "timestamp_hour": timestamp, "deviceID": deviceID },
update = { "$set": { } },
options = { "upsert": true };
update["$set"]["minutes."+ minute] = { "temperature": tempData };
deviceData.findOneAndUpdate(query, update, options, function(err, doc){
if(err) return res.send(500, {error: err});
return res.send("successfully saved");
});
Okay, so this works:
deviceData.findOne(query, function(err, doc) {
if(err) return done(err);
if(!doc){
data.save(function(err){
if(err) throw err;
res.json({"Result":"Success"});
});
} else {
doc.minutes[minute] = {temperature: tempData}
doc.save(function(err) {});
res.json(doc);
}
});
i have a problem with JSON.parse() in a NodeJS programm usging Express.
The problem is that when i get an external json using http.get for example like this:
[ { "Name" : "Parachutes", "Artist" : "Coldplay"}, { "Name" : "Lost!", "Artist": "Coldplay" } ]
When i do JSON.parse(ResponseStr) the i get the following json
[ { "Name" : "Parachutes", "Artist" : "Coldplay"}, { "Name" : "Lost?", "Artist": "Coldplay" } ]
The char ! is converting into ? when i do that JSON.parse, i want to have the same output as the original Name because when i want to use that name in a http.get('/example.com/album/Lost?') it is returning to me a 404 error.
This is mi my code:
function httpget(url,callback)
{
var str = "";
http.get(url, function(resp){
resp.on('data', function(chunk){
str += chunk;
});
resp.on('end', function(){
var obj = JSON2.parse(str);
callback(obj);
});
});
}
Edit 1:
I already using resp.setEncoding('utf8'); in my code, the problem is in in the JSON2.parse() (is same as JSON.parse()), before that i can do console.log(str) and the output will show "Lost!" but when i do JSON.parse() the output is like this "Lost?"
I am trying to make a post request with the MongoDB document returned from find query, as the request body in NodeJS.But on the server I'm getting the Error : Invalid JSON. Below is the document that I'm trying to POST
{
"_id" : ObjectId("5739a6bf3f1b41477570dc89"),
"taskCount" : 2,
"study" : "cod",
"phase" : "mansa2",
"rhimeTaskId" : "5739a6bec4567f6e737fd3db",
"recordId" : "5726f3cfc4567f6e737fc3ab",
"recordStudy" : "codstudy",
"recordPhase" : "mansa2",
"recordLanguage" : "Punjabi",
"recordScript" : "Latin",
"_state" : "CodingComplete",
"tasks" : [
{
"physician" : ObjectId("5739a6bd3f1b41477570dc78"),
"stage" : "Coding",
"result" : {
"cod" : "C15",
"feedback" : {
"narrativeLength" : "Adequate",
"positiveSymptomsIncluded" : "Only Positive",
"certainty" : "High"
},
"keywords" : [
"52 yr male, died of food pipe cancer, suffered pain upper abdomen, investigated,FNAC confirmed Cancer, Put on Chemotherapy, multiple cycles, died at home, had fever with chills occasionally"
]
}
},
{
"physician" : ObjectId("5739a6bd3f1b41477570dc79"),
"stage" : "Coding",
"result" : {
"cod" : "C15",
"feedback" : {
"narrativeLength" : "Inadequate",
"positiveSymptomsIncluded" : "Only Positive",
"certainty" : "High"
},
"keywords" : [
"severe pain abdomen, ultrasonography revealed food pipe cancer, chemotherapy given, died"
]
}
}
],
"__v" : 2
}
and here is the code that I wrote to make the POST request
var MongoClient = require('mongodb').MongoClient;
var request = require('request');
var assert = require('assert');
var cmeprovisioning= 'mongodb://localhost:27017/cmeprovisioning';
MongoClient.connect(cmeprovisioning, function(err, db) {
assert.equal(null, err);
var count=0;
console.log("Connected to cmeprovisioning");
var cursor =db.collection('rhimeReport').find(
{"study":"cod","phase":"mansa2","recordStudy":"codstudy",
"recordPhase":"mansa2","_state":"CodingComplete"
});
cursor.each(function(err, doc) {
assert.equal(err, null);
if (doc != null) {
console.dir(doc);
count=count+1;
request({url: "http://cme.host.net:8081/cme-provisioning/update",
method: "POST",json: true,
headers: {"content-type": "application/json"},
json: doc
},function(e,r,b){
console.log("POST Error "+count+" "+e)
console.log("POST Response "+count+" "+r)
console.log("POST BODY "+count+" "+b)
});
} else {
console.log("Some Error : "+err)
}
});
});
I also tried using JSON.stringify(doc), but still got the Invalid JSON error. Is there a way I can use mongo document returned by the find query and convert it to JSON to make the POST request.
I think those ObjectID is what making it an invalid JSON document.
Here's the actual answer:
If you want to convert a mongo object to JSON object.
There's a utility method in every mongo object toJSON
So you can simply do mongoResponseObject.toJSON() on the response object.
e.g.
Products.findById(id).then(res => {
const jsonRes = res.toJSON();
// Here jsonRes is JSON
})
Alternatively you can directly get the JSON object by using the .lean() like this.
Products.findById(id).lean().then(res => {
// Here res is JSON
})
you need to convert object id to string ie.
var result = {
"_id": ObjectId("5739a6bf3f1b41477570dc89"),
"taskCount": 2,
"study": "cod"
};
//now convert to string
result=result._id.toString();
//now you can use the result
Try this,
var cursor =db.collection('rhimeReport').find(
{"study":"cod","phase":"mansa2","recordStudy":"codstudy",
"recordPhase":"mansa2","_state":"CodingComplete"});
cursor.toString();
......
Hope this help.
Try this in robomongo
var cursor = db.getCollection('X').find({},{})
while(cursor.hasNext()) {
print(JSON.stringify(cursor.next()))
}