Insertion issue in Json Array object mongodb with Nodejs? - json

I am new to mongodb , I have below Json structure in mongodb ,
{
"_id" : ObjectId("59d62452a164b51d64b714c2"),
"folderName" : "Avinash 1234",
"tag" : "search",
"ismainFolder" : true,
"innerFolder" : [
{
"ismainFolder" : false,
"foldername" : "Test12",
"_id" : ObjectId("59d72246e66adf2cfcfdd6e6")
}
],
"innerFiles" : [
{
"filelocation" : "",
"isFolder" : false,
"filename" : "Penguins.jpg",
"_id" : ObjectId("59d7223de66adf2cfcfdd6e5")
},
{
"filelocation" : "",
"isFolder" : false,
"filename" : "Desert.jpg",
"_id" : ObjectId("59d72ff4e66adf2cfcfdd6ec")
},
{
"filelocation" : "",
"isFolder" : false,
"filename" : "Hydrangeas.jpg",
"_id" : ObjectId("59d731dfe66adf2cfcfdd6ed")
},
{
"filelocation" : "",
"isFolder" : false,
"filename" : "Chrysanthemum.jpg",
"_id" : ObjectId("59d73252e66adf2cfcfdd6ee")
}
],
"__v" : 0
}
For innerFiles array i need to insert the Tag field depending on the id ("_id" : ObjectId("59d7223de66adf2cfcfdd6e5")) . I used following nodeJs code but it adding as a new object . Please give me the solution .
exports.addTagForSearch = function (req, res, next) {
var tagDetails = req.body.tagDetails;
console.log("tagDetails", tagDetails);
console.log("tagDetails", tagDetails._id);
Repository.find({ _id: tagDetails._id, }, { innerFiles: { $elemMatch: { _id: tagDetails._id } } },function (err, response) {
$push: {
innerFiles: {
"tagName": tagDetails.tagname,
}
//"filelocation": tagDetails.filelocation
}
}, { upsert: true, new: true }, function (err, post) {
if (err) return next(err);
return res.status(200).json("success");
});
}
but above code inserting as a new object , Please give me solution please .

First I need to create a database for that I had a config.js file . Here is the code
module.exports = {
'secretKey': '12345-67890-09876-54321',
'mongoUrl' : 'mongodb://localhost:27017/innerFiles'
}
Next create a models folder and keep this order.js in it
// grab the things we need
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var folderSchema=new Schema({
ismainFolder:{
type:String,
//required:true,
default:''
},
foldername:{
type:String,
//required:true,
default:''
}
});
var innerSchema=new Schema({
filelocation:{
type:String,
//required:true,
default:''
},
isFolder:{
type:String,
//required:true,
default:''
},
filename:{
type:String,
//required:true,
default:''
}
});
var main= new Schema({
folderName:{type:String},
tag:{type:String},
ismainFolder:{type:String},
innerFolder:[folderSchema],
innerFiles:[innerSchema]
},{ strict: false });
var Order= mongoose.model('main', main);
// make this available to our Node applications
module.exports = Order;
Next create a routes folder and keep this orderRouter.js file in it
var express = require('express');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var Orders = require('../models/orders');
var app = express();
var orderRouter = express.Router();
orderRouter.use(bodyParser.json());
orderRouter.get('/get',function (req, res, next) {
Orders.find({}, function (err, order) {
if (err) throw err;
res.json(order);
});
})
orderRouter.post('/post',function (req, res, next) {
Orders.create(req.body, function (err, order) {
if (err) {
res.status(400).send('Bad request');
}
else{
console.log('order created!');
var id = order._id;
res.writeHead(200, {
'Content-Type': 'text/plain'
});
res.end('Added the order with id: ' + id);
}
});
})
orderRouter.get('/:orderId',function (req, res, next) {
Orders.findById(req.params.orderId, function (err, order) {
if (err) {
res.status(404).send('OrderId not found');
}
else{
res.json(order);
}
});
})
orderRouter.put('/addingField',function(req,res){
//var tagDetails = req.body;
console.log("tagDetails:"+req.body.subId);
console.log("tagname:"+req.body.tagname);
Orders.update(
{_id:req.body.mainId,'innerFiles._id':req.body.subId},
{$set:{'innerFiles.$.tagName':req.body.tagname}},
function (err, article) {
if (err) return console.log(err);
res.json(article);
});
});
app.use('/orders',orderRouter);
app.use(express.static(__dirname+'/public'));
module.exports = orderRouter;
Next create a app.js file this is the server code
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var config = require('./config');
mongoose.connect(config.mongoUrl);
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function () {
// we're connected!
console.log("Connected correctly to server");
});
var orderRouter = require('./routes/orderRouter');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
// passport config
app.use(passport.initialize());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/orders',orderRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.json({
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.json({
message: err.message,
error: {}
});
});
app.listen(3000,function(){
console.log("Server listening on 3000");
});
module.exports = app;
And run the server as node app.js.You can post data using this api http://localhost:3000/orders/post you need to use post method.Here is the sample input example for posting
{
"folderName" : "Avinash 1234",
"tag" : "search",
"ismainFolder" : "true",
"innerFolder" : [
{
"ismainFolder" : "false",
"foldername" : "Test12"
}
],
"innerFiles" : [
{
"filelocation" : "a",
"isFolder" : "false",
"filename" : "Penguins.jpg"
},
{
"filelocation" : "b",
"isFolder" : "false",
"filename" : "Desert.jpg"
},
{
"filelocation" : "c",
"isFolder" : "false",
"filename" : "Hydrangeas.jpg"
},
{
"filelocation" : "d",
"isFolder" : "false",
"filename" : "Chrysanthemum.jpg"
}
]
}
and here is the image for it
After posting data check that your data is stored in db or not.Here whatever the id I am giving in response is mainId . For that run this api http://localhost:3000/orders/get use get method for this. Collect the sub document id which is subId in our code.Sample Image for getting
After this here is the task of adding a new field to sub document for that use this api http://localhost:3000/orders/addingField and you need to use put method for this.Here is the input example
{
"mainId":"59dca6aff968a98478aaaa96",
"subId":"59dca6aff968a98478aaaa9a",
"tagname":"hello"
}
And Image for it
After completion of all these steps check into db.Here is the sample image for
it
That's it. Hope it helps.

Related

how to get a new value while parsing JSON?

Am trying to get data from an adaptive card (the name first) inside an async function and post it on mysql database. While using a post request i just get "{"name":""}" while parsing it. How do i properly fill this value?
async register(context) {
app.use(express.json());
app.use(bodyparser.json());
const SelectedCard5 = CARDS5[0];
await context.sendActivity({
text: 'processLogin(context)',
attachments: [CardFactory.adaptiveCard(SelectedCard5)]
})
await context.sendActivity
app.post('/id', async (req, res) => {
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
const fs = require('fs');
req.body = require('../Register.json');
var name = req.body.actions[0].$data["name"];
let username = '{"name":""}';
let z = JSON.stringify(name).replace(true, username);
let zz = JSON.parse(username);
mysqlConnection.query("INSERT INTO users(name) VALUES('" + username + "')", function (err, result) {
console.log("Yeah! record inserted");
console.log(z);
console.log(zz);
}); res.send(username);
});
} }
//the JSON field am trying to replace>>>>>>>>>
"actions": [
{
"type": "Action.Submit",
"title": "add new user",
"$data": {
"name": true,
"email": true,
"password": true
}
},

Sequelize throw AssertionErrors with MySQL

I'm building an API using nodejs, sequelize, dan MySQL database (10.1.21-MariaDB). When I tried to do some PATCHing (updating data), it throws AssertionErrors, but it works fine with POST (inserting data).
Here's my patch code:
const express = require('express');
const router = express.Router();
const brandModel = sequelize.define('tbl_brand', {
brand_name: {
type: Sequelize.STRING,
allowNull: false
},
}, {
freezeTableName: true,
});
router.patch('/:id', (req, res, next) => {
const id = req.params.id;
const newModel = {
brand_name: req.body.brand_name
};
sequelize.authenticate().then(() => {
const promise = brandModel.update(newModel, {brand_id: id});
return promise.then(function(item){
res.status(201).json({
success: true,
result: item
});
});
})
.catch(err => {
res.status(500).json({
success: false,
result: err
});
});
});
I use postman and access it like this:
http://localhost:3000/brand/1
With Raw JSON:
{
"brand_name" : "Adidasssss"
}
And here's the result:
{
"success": false,
"result": {
"generatedMessage": false,
"name": "AssertionError [ERR_ASSERTION]",
"code": "ERR_ASSERTION",
"expected": true,
"operator": "=="
}
}
What could be the problem?
Nevermind... I was careless, I was updating an empty instance called brandModel. It should be searched first then do the update

How to get results from MySql DB using node.js MySQL and send them back to API.ai - DialogFlow

I am having issues retrieving and sending results from a MySql database to API.ai. The concrete question is how to wait for the results to be available, and then send the results in the Json object back to API.ai
This is what I have:
In the webhook or service, after receiving the Json request, I call a method:
if (action === 'get.data') {
// Call the callDBJokes method
callDB().then((output) => {
// Return the results to API.AI
res.setHeader('Content-Type', 'application/json');
res.send(JSON.stringify(output));
}).catch((error) => {
// If there is an error let the user know
res.setHeader('Content-Type', 'application/json');
res.send(JSON.stringify(error));
});
}
which calls the method callDB() where the database call is executed:
function callDB() {
return new Promise((resolve, reject) => {
try {
var connection = mysql.createConnection({
host: "127.0.0.1",
user: "root",
password: "x",
database: 'y'
});
connection.query('SELECT 1 + 1 AS solution', function (error, results, fields) {
if (!error) {
let response = "The solution is: " + results[0].solution;
response = response.toString();
let output = {'speech': response, 'displayText': response};
console.log(output);
resolve(output);
} else {
let output = {'speech': 'Error. Query Failed.', 'displayText': 'Error. Query Failed.'};
console.log(output);
reject(output);
}
});
connection.end();
} catch (err) {
let output = {'speech': 'try-cacth block error', 'displayText': 'try-cacth block error'};
console.log(output);
reject(output);
}
}
);
}
I get a Json response in API.ai like:
{
"id": "5daf182b-009f-4c11-a654-f2c65caa415e",
"timestamp": "2017-08-29T07:24:39.709Z",
"lang": "en",
"result": {
"source": "agent",
"resolvedQuery": "get data",
"action": "get.data",
"actionIncomplete": false,
"parameters": {},
"contexts": [
{
"name": "location",
"parameters": {
"date": "",
"geo-city": "Perth",
"date.original": "",
"geo-city.original": "perth"
},
"lifespan": 2
},
{
"name": "smalltalkagentgeneral-followup",
"parameters": {},
"lifespan": 2
}
],
"metadata": {
"intentId": "4043ad70-289f-441c-9381-e82fdd9a9985",
"webhookUsed": "true",
"webhookForSlotFillingUsed": "false",
"webhookResponseTime": 387,
"intentName": "smalltalk.agent.general"
},
**"fulfillment": {
"speech": "error",
"displayText": "error",
"messages": [
{
"type": 0,
"speech": "error"**
}
]
},
"score": 1
},
**"status": {
"code": 200,
"errorType": "success"**
},
"sessionId": "c326c828-aa47-490c-9ca0-37827a4e348a"
}
I am getting only the error message but not the result from the database. I read that it could be done using callbacks as well, but I could not figure it out yet. I can see that the database connection is working, because the logs of the connections shows the connection attempts.
Any help will be appreciated. Thanks.
Solved by declaring the var mysql = require('mysql'); as const mysql = require('mysql'); not inside the function, but before the exports.myfunction declaration. Working example code to get results from MySql DB using node.js MySQL, and send them back to API.ai is as follows:
'use strict';
const mysql = require('mysql');
exports.her_goes_your_function_name = (req, res) => { //add your function name
//Determine the required action
let action = req.body.result['action'];
if (action === 'get.data') {
// Call the callDBJokes method
callDB().then((output) => {
// Return the results of the weather API to API.AI
res.setHeader('Content-Type', 'application/json');
res.send(JSON.stringify(output));
}).catch((error) => {
// If there is an error let the user know
res.setHeader('Content-Type', 'application/json');
res.send(JSON.stringify(error));
});
}
};
function callDB() {
return new Promise((resolve, reject) => {
try {
var connection = mysql.createConnection({
host: "127.0.0.1",
user: "your_user",
password: "your_pass",
database: "your_DB"
});
connection.query('SELECT 1 + 1 AS solution', function (error, results, fields) {
if (!error) {
let response = "The solution is: " + results[0].solution;
response = response.toString();
let output = {'speech': response, 'displayText': response};
console.log(output);
resolve(output);
} else {
let output = {'speech': 'Error. Query Failed.', 'displayText': 'Error. Query Failed.'};
console.log(output);
reject(output);
}
});
connection.end();
} catch (err) {
let output = {'speech': 'try-cacth block error', 'displayText': 'try-cacth block error'};
console.log(output);
reject(output);
}
}
);
}

How to show mongodb data as JSON? (NodeJS)

So what I'm asking is how I would show my MongoDB data as JSON on a seprate page? So far I have a database called 'movies' which has a table that contains a bunch of movie titles, rating and stock.
As seen here:
{ "_id" : ObjectId("55e579d30bb58af007d4d8f3"), "movieTitle" : "Iron Man", "rating" : "Excellent", "stock" : "Yes", "sort" : "iron man", "__v" : 0 }
{ "_id" : ObjectId("55e59c3d1d19a3d20ae67a9c"), "movieTitle" : "A Bittersweet Life", "rating" : "Poor", "stock" : "Yes", "sort" : "a bittersweet life", "__v" : 0 }
{ "_id" : ObjectId("55e59c441d19a3d20ae67a9d"), "movieTitle" : "A Team", "rating" : "Okay", "stock" : "No", "sort" : "a team", "__v" : 0 }
I also have the page I want the json to be displayed on:
var express = require('express');
var mongoose = require('mongoose');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('data', {});
});
module.exports = router;
Schema:
var movieSchema = new Schema({
movieTitle: {
type: String,
required: true
},
rating: {
type: String
},
stock: {
type: String,
required: true
},
sort: {
type: String
}
});
Can someone help me out?
I think you could do something like this:
var express = require('express');
var mongoose = require('mongoose');
var router = express.Router();
var movieSchema = new Schema({
movieTitle: {
type: String,
required: true
},
rating: {
type: String
},
stock: {
type: String,
required: true
},
sort: {
type: String
}
});
var Movie = mongoose.model('Movie', movieSchema, 'movies');
mongoose.connect('localhost', function(err, res){
})
/* GET home page. */
router.get('/', function(req, res, next) {
Movie.find({}, function(err, movies) {
res.render('data', movies);
})
});
module.exports = router;
For those who want to see how I got it working:
/* GET home page. */
router.get('/', function(req, res, next) {
// Get Movie schema for use
var Movie = mongoose.model('movie');
// Query all records using aggregate
Movie
.aggregate()
.match({})
.sort({ sort: 1 })
.exec(function(err, movies) {
// Handle errors
if (err) {
return res
.status(500)
.json({
error: err
});
}
// Manipulate movies to tidy up keys
movies.forEach(function (movie) {
movie.id = movie._id;
delete movie._id;
delete movie.__v;
delete movie.sort;
});
return res.json(movies);
});
});

How to Use nodes callback when i want to build a JSON Object Like Below

I have just started coding with node.js, I understand that node.js is asynchronous but not sure how to deal with this problem.
I'm querying mysql and building a JSON as follows:
var mysql = require('mysql');
var async = require('async');
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '',
database : 'hungryna_hungry_database',
insecureAuth : true
});
var obj={
"zone":[],
};
var zonearray=new Array();
connection.query('SELECT id,name FROM zone LIMIT 100', function(err, rows) {
var ck=new Array();
for(i=0; i < rows.length; i++){
var zoneObj={};
var zone=rows[i];
zoneObj.id=zone.id;
zoneObj.name=zone.name;
ck.push({
"id":zoneObj.id,
"name":zoneObj.name
});
build_actor(zoneObj.id,function(err,area){
if(!err){
//zonearray=ck;
//obj.zone=zonearray;
console.log(JSON.stringify(ck));
}
});
}
});
function build_actor(zoneid,cb){
connection.query('SELECT id,name FROM area WHERE zone_id='+zoneid+';',
function(err, a) {
var ak =new Array();
for(var i in a)
{
ak.push({
"id":a[i].id,
"name":a[i].name
});
}
cb (null,ak);
});
My output is below:
[{"id":1,"name":"Gulshan-Banani-Baridhara-DOHS"},{"id":2,"name":"Uttara"},{"id":
4,"name":"Dhanmondi-Lalmatia-Mohammadpur"}]
[{"id":1,"name":"Gulshan-Banani-Baridhara-DOHS"},{"id":2,"name":"Uttara"},{"id":
4,"name":"Dhanmondi-Lalmatia-Mohammadpur"}]
[{"id":1,"name":"Gulshan-Banani-Baridhara-DOHS"},{"id":2,"name":"Uttara"},{"id":
4,"name":"Dhanmondi-Lalmatia-Mohammadpur"}]
Output I want is below:
{
"zone1":[
{
"id":1,
"name":"a",
"area":[
{
"id":1,
"name":"area1"
},
{
"id":2,
"name":"area2"
}
]
},
{
"id":2,
"name":"b",
"area":[
{
"id":1,
"name":"area1"
},
{
"id":2,
"name":"area2"
}
]
}
]
}