I'm working with SAP CDS.
In data-model.cds I have:
namespace my.bookshop;
using { Country, managed } from '#sap/cds/common';
entity Books {
key ID : Integer;
title : localized String;
author : Association to Authors;
stock : Integer;
}
entity Authors {
key ID : Integer;
name : String;
books : Association to many Books on books.author = $self;
}
entity Orders : managed {
key ID : UUID;
book : Association to Books;
country : Country;
amount : Integer;
}
In cat-service.cds I have:
using my.bookshop as my from '../db/data-model';
service CatalogService {
entity Books #readonly as projection on my.Books;
entity Authors #readonly as projection on my.Authors;
entity Orders #insertonly as projection on my.Orders;
}`In`cat-service.js`: `"use strict";
var hana = require("#sap/hana-client");
var connOptions = {
serverNode: "xxxxxxxxx.hanacloud.ondemand.com:443",
encrypt: "true",
sslValidateCertificate: "false",
uid: "DBADMIN",
pwd: "mypssw",
};
var dbConnection = hana.createConnection();
dbConnection.connect(connOptions, function (err) {
if (err) throw err;
else{
console.log("Connection Done.")
}
});
How to query my Books entity? I don't know how to check if the schema is right, so I post a picture of my SAP HANA CLOUD Cockpit.
This is my SAP HANA Cloud:
I tried:
var statement = "SELECT \* FROM my.bookspace.Books";
dbConnection.exec(statement, function (err, result) {
if (err) {
console.error(err);
res.status(500).send(err.message);
} else {
res.send(result);
}
});
But:
Error: invalid data source name: MY: line 1 col 15 (at pos 14)
at Socket.<anonymous> (/home/user/projects/my-bookshop/node_modules/#sap/hana-client/lib/index.js:53:13)
at Socket.emit (node:events:527:28)
at addChunk (node:internal/streams/readable:315:12)
at readableAddChunk (node:internal/streams/readable:289:9)
at Socket.Readable.push (node:internal/streams/readable:228:10)
at Pipe.onStreamRead (node:internal/stream_base_commons:190:23) {
code: 471,
sqlState: 'HY000'
}
Related
when a user login and clicks the cart button i want to see the products which added by the user in my console. in my cart collection there is some documents which contain userid and products id.so when a user clicks the cart link on the navbar i want to see the products which added to the cart by the user in my console but instead of this am getting this error.this is the first time i using aggregate in monogodb
getCartProduct in usehelpers.js
getCartProducts: userId => {
return new Promise(async (resolve, reject) => {
let CartItems = await db
.get()
.collection(Collection.CART_COLLECTIONS)
.aggregate([
{
$match: { user: objectId(userId) },
},
{
$lookup: {
from: Collection.PRODUCT_COLLECTIONS,
let: { prodList:'$products' },
pipeline: [
{
$match: {
$expr: {
$in: ['$_id', '$$prodList'],
},
},
},
],
as: 'CartItems',
},
},
])
.toArray();
resolve(CartItems);
});
},
};
arguments passed from user.js
router.get('/cart',verifyLogin,async(req,res)=>{
let products = await userHelpers.getCartProducts(req.session.user._id)
console.log(products);
res.render('user/cart')
})
console error
MongoServerError: PlanExecutor error during aggregation :: caused by :: $in requires an array as a second argument, found: objectId
at Connection.onMessage (C:\Users\krish\OneDrive\Desktop\project mern stack\webdev-challenge\node_modules\mongodb\lib\cmap\connection.js:210:30)
at MessageStream.<anonymous> (C:\Users\krish\OneDrive\Desktop\project mern stack\webdev-challenge\node_modules\mongodb\lib\cmap\connection.js:63:60)
at MessageStream.emit (events.js:400:28)
at processIncomingData (C:\Users\krish\OneDrive\Desktop\project mern stack\webdev-challenge\node_modules\mongodb\lib\cmap\message_stream.js:132:20)
at MessageStream._write (C:\Users\krish\OneDrive\Desktop\project mern stack\webdev-challenge\node_modules\mongodb\lib\cmap\message_stream.js:33:9)
at writeOrBuffer (internal/streams/writable.js:358:12)
at MessageStream.Writable.write (internal/streams/writable.js:303:10)
at Socket.ondata (internal/streams/readable.js:731:22)
at Socket.emit (events.js:400:28)
at addChunk (internal/streams/readable.js:293:12)
I need to create a separate database for each entity in my client's app.
I'm going to determine the database name according
to the subdomain from which the request is coming from.
How can I achieve that and connect dynamically to a database using nestjs and mongoose?
UserService
async findOneByEmail(email: string, subdomain: string): Promise<User | any> {
const liveConnections = await Databases.getConnection(subdomain)
const user = await liveConnections.model(User.name, UserSchema).find()
// { 'securityInfo.email': email }
if (!user)
throw new HttpException(
{
status: HttpStatus.BAD_REQUEST,
error: 'user not found',
field: 'user',
},
HttpStatus.BAD_REQUEST
)
return user
}
class that I create
class DataBases extends Mongoose {
private clientOption = {
keepAlive: true,
useNewUrlParser: true,
useUnifiedTopology: true,
}
private databases: { [key: string]: Connection } = {}
private getConnectionUri = (companyName = '') =>
`mongodb+srv://${process.env.MONGODB_USERNAME}:${process.env.MONGODB_PASSWORD}#cluster0.2lukt.mongodb.net/${companyName}?retryWrites=true&w=majority`
public async getConnection(companyName = ''): Promise<Connection> {
const connection = this.databases[companyName]
return connection ? connection : await this.createDataBase(companyName)
}
private async createDataBase(comapnyName = ''): Promise<Connection> {
// create new connection and if the database not exists just create new one
const newConnection = await this.createConnection(
this.getConnectionUri(comapnyName),
this.clientOption
)
this.databases[comapnyName] = newConnection
return newConnection
}
}
I fix it. the DataBases Class that I create works really great and if you know a better way please tell me .
what I had to change is the way I use the connection to MongoDB.
and now I can connect to different databases depends on the subdomain.
I hope it will help someone!
UserService
async findOneByEmail(email: string, subdomain: string): Promise<User | any> {
const liveConnections = await Databases.getConnection(subdomain)
const user = await liveConnections
.model(User.name, UserSchema)
.findOne({ 'securityInfo.email': email })
.exec()
if (!user)
throw new HttpException(
{
status: HttpStatus.BAD_REQUEST,
error: 'user not found',
field: 'user',
},
HttpStatus.BAD_REQUEST
)
return user
}
I am using postgresql database. I am getting this error "invalid input syntax for type integer" while inserting data into table via express api but the same query is successfully run in pgAdmin.
const file = require('../../Pool');
const pool = file.pool;
const createClass= (req,res)=>{
pool.query("insert into classes(class_name,school_id) values ( 'ICS' , (select id from schools where admin_id = 1))",[className,adminId],
(err,result)=>{
if(err){
console.log('err');
throw err
}
res.status(200).send({"isCreated":true})
}
)
}
module.exports = {
createClass
}
So, I'm new to SQL and I'm trying to seed my POSTGRESQL database. My invitations table is a join table that is supposed to take in the user.id and the event.id I have a seed.js file that was moving along fine until I get this error:
$ node db/seeds/seed.js
SELECT * FROM users WHERE id = 1
SELECT * FROM events WHERE id = 1
N
{ error: syntax error at or near "N"
at Connection.parseE (/Users/student_105/Desktop/DateTime/node_modules/pg/lib/connection.js:546:11)
at Connection.parseMessage (/Users/student_105/Desktop/DateTime/node_modules/pg/lib/connection.js:371:19)
at Socket.<anonymous> (/Users/student_105/Desktop/DateTime/node_modules/pg/lib/connection.js:114:22)
at emitOne (events.js:115:13)
at Socket.emit (events.js:210:7)
at addChunk (_stream_readable.js:266:12)
at readableAddChunk (_stream_readable.js:253:11)
at Socket.Readable.push (_stream_readable.js:211:10)
at TCP.onread (net.js:585:20)
name: 'error',
length: 89,
severity: 'ERROR',
code: '42601',
detail: undefined,
hint: undefined,
position: '1',
internalPosition: undefined,
internalQuery: undefined,
where: undefined,
schema: undefined,
table: undefined,
column: undefined,
dataType: undefined,
constraint: undefined,
file: 'scan.l',
line: '1086',
routine: 'scanner_yyerror' }
I don't see an N anywhere in my code and I don't want to start messing with a module in case I mess everything up.
here's my seed.js
const User = require('../../models/user');
const Event = require('../../models/Event');
const Invitation = require('../../models/invitation');
// get this to work at some point
// const newUser = User.create({"name": "Andrea McKenzie",
// "phone_number": "9176746154",
// "email": "mckenzie.andrea.m#gmail.com"});
// const newUser2 = User.create({"name":"Anthony Pagan",
// "phone_number":"7189169523",
// "email":"a.pagan90#yahoo.com"});
const newUser = User.findById(1);
const newEvent = Event.findById(1);
Promise.all([newEvent,newUser])
.then(array => {
const event = array[0];
const user = array[1];
return Invitation.create(event.id, user.id);
})
.then(invitation => {
console.log(invitation)
})
.catch(err =>
console.log(err)
)
What might this be and how can I fix it? And how can I eventually seed my table?
edit: adding Invitation.js
const db = require('../db/config');
const Invitation = {};
Invitation.create = (userId,eventId,status = "pending") => {
return db.one(`INSERT INTO invitations (event_id,user_id) VALUES ($1,$2)
RETURNING *` [userId,eventId]);
}
module.exports = Invitation;
In my main file server.js I have following function:
server.js
const mongoose = require('mongoose');
const SmallRounds = require('./models/smallrounds.js');
function initRound(){
logger.info('Initializing round...');
SmallRounds.getLatestRound((err, data) => {
[...]
});
}
the function getLatestRound() gets exported in my mongoose model smallrounds.js
smallrounds.js
const mongoose = require('mongoose');
const config = require('../config.js');
const SmallRoundsSchema = mongoose.Schema({
[...]
});
const SmallRounds = module.exports = mongoose.model('SmallRounds', SmallRoundsSchema);
module.exports.getLatestRound = function(callback){
SmallRounds.findOne().sort({ created_at: -1 }).exec((err, data) => {
if(err) {
callback(new Error('Error querying SmallRounds'));
return;
}
callback(null, data)
});
}
But when I call initRound() I get following error:
TypeError: SmallRounds.getLatestRound is not a function
at initRound (E:\Projects\CSGOOrb\server.js:393:14)
at Server.server.listen (E:\Projects\CSGOOrb\server.js:372:2)
at Object.onceWrapper (events.js:314:30)
at emitNone (events.js:110:20)
at Server.emit (events.js:207:7)
at emitListeningNT (net.js:1346:10)
at _combinedTickCallback (internal/process/next_tick.js:135:11)
at process._tickCallback (internal/process/next_tick.js:180:9)
at Function.Module.runMain (module.js:607:11)
at startup (bootstrap_node.js:158:16)
at bootstrap_node.js:575:3
Why is this happening? I don't think that I have circular dependencies and have not misspelled anything. Thanks :)
That's not how you add methods to Mongoose models/schemas.
Try this:
const mongoose = require('mongoose');
const config = require('../config.js');
const SmallRoundsSchema = mongoose.Schema({
[...]
});
SmallRoundsSchema.statics.getLatestRound = function(callback){
this.findOne().sort({ created_at: -1 }).exec((err, data) => {
if(err) {
callback(new Error('Error querying SmallRounds'));
return;
}
callback(null, data)
});
}
const SmallRounds = module.exports = mongoose.model('SmallRounds', SmallRoundsSchema);
You can read the documentation here: http://mongoosejs.com/docs/guide.html, in the section "Statics". There are other, better ways of achieving the same result, but this will get you started.
I was using upper-case module, and getting error TypeError: upperCase is not a function
l
et upperCase =require("upper-case") ;
res.end(upperCase("Hello World"));
as every tutorial written in this way.
I changed it to
res.end(upperCase.upperCase("Hello World"));
and working fine