Null value in column "title" of relation "blog" violates not-null constraint - postgresql

I'm building a little blog using express js for the backend, but I'm facing an issue: I get this error in the console
null value in column "contentblog" of relation "blog" violates not-null constraint
Code:
const connection = require('../DatabaseConnection/db')
module.exports.Add = function (req, res) {
const blog = {
title: req.body.title,
contentBlog: req.body.contentBlog,
}
connection.query('INSERT INTO blog(contentBlog) values($1)', [blog.contentBlog], function (error, results, fields) {
if (error) {
res.json({
status: false,
message: 'there are some errors with the query'
})
console.log(error)
} else {
res.json({
status: true,
data: results,
message: 'Post has been added successfully'
})
}
});
}

You are trying to insert a null or undefined variable into your postgresql table.
Check the value of req.body.contentBlog.

Related

MongoDB; /delete_api_keys

I have a case study that requires to write some endpoints to communicate with a data set stored in MongoDB.
Below is my trial to make up the query to delete multiple API keys, and it returns me TypeError: Cannot read properties for undefined (reading 'filter').
I do not understand if it's not reading an Object I call on filter, or the method .filter() itself.
I am learning; always happy to learn from constructive criticism.
Thanks in advance!
app.options("/delete_api_keys", cors());
app.delete("/delete_api_keys", auth(["admin"]), (req, res) =>{
const readings = db.collection("access")
const access_ids = req.body.keys_to_delete
.filter((access_id) => {ObjectID.isValid(access_id)})
.map((access_id) => {ObjectID.isValid(access_id)})
// Error - one of the objects I call on .filter is undefined
readings.deleteMany({ _id: { $in: access_ids } })
.then((query_result) => {
res.status(200).json({
code: 200,
message: "api keys deleted",
})
})
.catch(error => {
res.status(500).json({
code: 500,
message: "Failed to delete api key" + error,
})
})
})
Below the snapshot of Postman trying to delete multiple ObjectID using the authorised api key
[![enter image description here](https://i.stack.imgur.com/SzXbv.png)](https://i.stack.imgur.com/SzXbv.png)

Sequelize (Postgres) always 'returning' null for second index (whether creating or updating)

Trying to correctly troubleshoot HTTP status codes and responses on upsert. I've scoured SO and google to find examples of this behavior, but the answers are always really old (pre Sequelize 6 era).
From what I gather over at Sequelize docs, UPSERT returns Promise<Model,boolean | null> and additionally For SQLite/Postgres, created value will always be 'null'. But apparently for me, whether it created/didn't update/updated, it always returns null
Am I correctly understanding that boolean return will return for update(T)/no update(F) and null for creation? Or will it only return null whether create|update|no update for postgres users?
This is MY expected return behavior:
data: [
{
id: 64920,
...etc...
},
null // null = created
],
data: [
{
id: 64921,
...etc...
},
false // false = no update (data is the same)
],
data: [
{
id: 64922,
...etc...
},
true // true = update complete (some data was new)
]
Sample controller upsert command:
exports.createOne = async (req, res, next) => {
Trip.upsert({
id: req.body.id,
...etc...
},{returning: true } // not needed, default in Sequelize =< 6.0
)
.then(function (test) {
if (test) {
res.status(200);
res.send("Successfully stored");
} else {
res.status(200);
res.send("Successfully inserted");
}
})
.catch((err) => {
res.status(500).json({ error: err.message });
});
};
Anyone have examples or suggestions to properly implement this?
Thank you!

mongoose.connect() is not creating a database?

I am using mongoose.connect() method but it couldn't created a DB ,i did even insert some documents in
db by using insertMany() but it neither giving me any error nor creating a DB as when i checked my mongo Shell todolistDB is not created .
const express = require('express')
const bodyParser = require('body-parser')
const mongoose = require('mongoose')
mongoose.connect('mongodb://localhost:27017/todolistDB', {
useNewUrlParser: true,
useUnifiedTopology: true },
function (err) {
if (err) {
console.log(err);
} else {console.log('server is connected');}})
const itemsSchema = mongoose.Schema({name: {type: String,required: true }})
const Item = mongoose.model('Item', itemsSchema)
const item1 = new Item({name: 'Welcome to your todo list!'})
const item2 = new Item({name: 'Hit + button to add new item'})
const item3 = new Item({name: '<-- click to delete a item!'})
const defaultItems = [item1, item2, item3]
app.get('/', function (req, res) {
Item.find({}, function (err, result) {
if (defaultItems.length===0) {
**even after insertmany method todolistDB is not created**
Item.insertMany(defaultItems, function (err) {
if (err) {
console.log(err);
} else {
console.log('new record inserted successfully!');}});
} else {
res.render('list', {listTitle: 'today',latestItems: result}) }
** when I used insertMany outside app.get() method then all records was inserted, I just started learning mongoDB sorry in advanced if it was a silly mistake **
detailed answer would be appreciated!
Consider the following three lines of your code:
[1] const defaultItems = [item1, item2, item3]
[2] Item.find({}, function (err, result) {
[3] if (defaultItems.length===0) {
In [2] you are doing a query, presumably it returns no results and you get to [3]. However in [3] you are referencing the fixed set defined in [1] which is of length 3. Thus the if statement in [3] is never entered.
The code is pretty fine.
mongoose.connect() call is fine. Since you are writing it in Promise form, issue is Unhandled Promise Rejection for connection failure.
Console the error, the error message would give us better glimpse.
Coming to the error possibilities, it is likely to happen if you use middleware handler app.use or router.use.
Please console the error, drop down the error message. So that I can help you further.
You Can Follow This Code
mongoose.connect('mongodb://localhost:27017/todolistDB', {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
useFindAndModify: false
})
mongoose.connection.on("connected", () => {
console.log("Mongodb connected")
})
mongoose.connection.on("error", errMsg => {
console.log("Error connecting database. Msg: " + errMsg)
})

Issue Populating Filter Value for AG Grid agSetColumnFilter

I'm trying to populate the value for the agSetColumnFilter, but I'm getting an error that I cannot find anything where in documentation (or anywhere online). Has anyone ever run into this issue?
This is what the column definition looks like:
columnDefs.push({
headerName: col.name,
field: col.name,
def: col,
rowGroup: k < groupedColumnCount ? true : false,
pinned: k < _this.groupBy.length ? 'left' : null,
lockPinned: k < _this.groupBy.length ? true : false,
hide: k < groupedColumnCount ? true : false,
suppressToolPanel: _this.groupBy.length ? true : false,
valueGetter: function(data){
if(data.data){
var def = data.colDef.def;
var value = data.data[data.colDef.field];
if(value){
return value.value;
}else{
return null;
}
}else{
return data.value;
}
},
valueFormatter: function(data){
if(data.data){
var def = data.colDef.def;
var value = data.data[data.colDef.field];
if(!value) return null;
if(value.formatted){
_this.cache[data.colDef.field + value.value] = value.formatted;
}
return value.formatted ? value.formatted : value.value;
}else{
if(_this.cache[data.colDef.field + data.value]){
return _this.cache[data.colDef.field + data.value];
}else{
return data.value;
}
}
},
keyCreator: function(params){
console.log(params);
},
filter: 'agSetColumnFilter',
filterParams: {
values: function (params) {
params.success([{
$uri: 'nhuihi',
value: {
$value: 'some text'
}
}]);
}
}
});
I'm only printing out keyCreator params for now since I don't know what will actually be available in the data. The idea is that I can set values using complex objects returned from the server and display a formatted value instead of a key. This is the error I'm getting.
ag-grid-enterprise.min.noStyle.js:formatted:27684 Uncaught TypeError: Cannot read property 'onFilterValuesReady' of undefined
at t.setFilterValues (ag-grid-enterprise.min.noStyle.js:formatted:27684)
at e.modelUpdatedFunc (ag-grid-enterprise.min.noStyle.js:formatted:27609)
at e.onAsyncValuesLoaded (ag-grid-enterprise.min.noStyle.js:formatted:27917)
at values (comparison-table-v7.js:1253)
at e.createAllUniqueValues (ag-grid-enterprise.min.noStyle.js:formatted:27909)
at new e (ag-grid-enterprise.min.noStyle.js:formatted:27867)
at t.initialiseFilterBodyUi (ag-grid-enterprise.min.noStyle.js:formatted:27608)
at t.init (ag-grid-enterprise.min.noStyle.js:formatted:18945)
at e.initialiseComponent (ag-grid-enterprise.min.noStyle.js:formatted:10602)
at e.createAgGridComponent (ag-grid-enterprise.min.noStyle.js:formatted:10574)
Here's a test case for it as well. I simply modified the example by AG Grid. https://plnkr.co/edit/GURQHP0KKFpJ9kwaU83M?p=preview
If you open up console, you will see an error when you click on Athletes filter.
Also reported on GitHub: https://github.com/ag-grid/ag-grid/issues/2829
If you need to configure filter values without async requests
filterParams: {
values: getFilterValuesData()
}
getFilterValuesData(){
//data preparation
//little bit modified sample to present that you can handle your logic here
let data = [];
[
'John Joe Nevin',
'Katie Taylor',
'Paddy Barnes',
'Kenny Egan',
'Darren Sutherland',
'Margaret Thatcher',
'Tony Blair',
'Ronald Regan',
'Barack Obama'
].forEach(i=>{
data.push(i);
});
return data;
}
If it requires to make an async request for data preparation you can use callback function:
filterParams: {
values: (params)=>{
setTimeout(()=>{ -- setTimeout on this case only for async request imitation
params.success(['value 1', 'value 2'])
}, 5000)
}
}
Notice: params.success(...) should be used only with an async request
Doc: ag-grid Asynchronous Values

Monogdb update function works on terminal but not on metoer server

I'm trying to figure out what I'm doing wrong here with absolutely no luck.
db.attendances.update({ _id: 'hRs6LfAqPBmy4ZNuH' }, { $set: { absentParentOrGuardianDate: undefined } })
If I run this update command in the terminal shell using 'meteor mongo' absentParentOrGuardianDate is removed from the document, however, if I run the same code, slightly changed for meteor, on the meteor server I get an error.
Attendances.update({ _id: 'hRs6LfAqPBmy4ZNuH' }, { $set: { absentParentOrGuardianDate: undefined } });
The error is:
{isClientSafe: true, error: 500, reason: "Internal server error", details: undefined, message: "Internal server error [500]", …}
Can someone please tell me what I'm missing here.
import { _ } from 'meteor/underscore';
const updateDoc = {};
_.each(yourObj, (value, key) => { // I'm using underscore to help loop through the object
if (value) {
updateDoc.$set[key] = value;
} else {
updateDoc.$unset[key] = value;
}
});
yourCollection.update(yourSelector, updateDoc);