How can I do an updateItem in a nested element in dynamodb? - javascript

I have and map structure stored at dynamodb, an I would like to add another attribute inside school object
something like:
{
name: 'Felipe'
uid: 112233,
data: {
structure: {
school: {
name: 'beta'
}
}
}
}
previously the add_year did not was a part of the structure, so this part is new
school: {
name: 'beta'
add_year: '2020'
}
How can I accomplised that?
I've tried the following solutions, without success
(async ()=>{
try {
let teste = await dynamoDb.updateItem({
TableName: 'test',
Key: {
uid: "112233"
},
UpdateExpression: "SET data.#structure.#school = list_append(#structure, :attrValue)",
ExpressionAttributeNames: {
"#data": "data",
"#structure": "structure",
"#school": "school",
},
ExpressionAttributeValues: {
":school":{
"add_year": 2020
}
},
ReturnValues:"UPDATED_NEW "
})
console.log('update',teste)
} catch (error) {
console.log(error)
}

Felipe, did you see the AWS documentation about this topic?
I think this code can work for you:
(async () => {
try {
var params = {
TableName: 'test',
Key: {
"uid": "112233"
},
UpdateExpression: "SET data.structure.school.add_year = :year)",
ExpressionAttributeValues: {
":add_year": 2020
},
ReturnValues: "UPDATED_NEW"
}
dynamoDb.update(params, (err, data) => {
if (err) {
console.error("Unable to update item. Error JSON:", JSON.stringify(err, null, 2));
} else {
console.log("UpdateItem succeeded:", JSON.stringify(data, null, 2));
}
})
} catch (error) {
console.log(error)
}
})

const { DocumentClient } = require('aws-sdk/clients/dynamodb');
const documentClient = new DocumentClient({
region: 'us-east-1',
});
try {
let add_year= '2020'
let teste = documentClient.update({
TableName: 'test',
Key: {
uid: "112233"
},
UpdateExpression: `SET #data.structure.school= :add_year`,
ExpressionAttributeValues: {
':add_year': add_year
},
ExpressionAttributeNames: {
"#data": "data"
},
ReturnValues:"ALL_NEW"
}).promise()
teste.then(t => console.log(t));
} catch (error) {
console.log(error)
}

Related

Mongoose mixed Type object array, can findOneAndUpdate

I have a controller edit card which updates the fields of cardsArray object.
cardsArray is mixed type object as fileds of each card object is different so i am storing mixed.type
Althought pushing new card using addCard controller works perfectly
But when edit card controller is called, it gives type error
When edit Controlller is callled is gives following error:
TypeError: Cannot read properties of null (reading 'cardsArray')
// Schema
const userSchema = new mongoose.Schema(
{
name: {
type: String,
required: true,
},
email: {
type: String,
required: true,
},
password: {
type: String,
required: true,
},
cardsArray: [{ type: mongoose.Schema.Types.Mixed }],
}
);
//__Mongodb Data
{
"_id": {
"$oid": "63b43ab32fc8d3c100cafecc"
},
"name": "usern_name",
"email": "pr****#gmail.com",
"password": "$2b$12$3nwifHakrBu94BwLXAC4Nu16Kw0.xyW8vAIPTMSgY7cYttVklDIZq",
"cardsArray": [
{
"title": "some_title",
"category": "Bank",
"cardHolder": "some_name",
"cardNumber": "54545454",
"expiry": "23/01",
"cvv": "***",
"logoIndex": 72,
"isFavourite": false,
"_id": {
"$oid": "63b83cc77288d277ef359533"
}
}
],
"loginIdsArray": [],
"docsArray": [],
"activitiesArray": [],
"__v": 0
}
// Add Card Controller.js___
addCard: async (req, res) => {
console.log(req.body.data, req.body.user_id)
// console.log('obj_id', newObjectId)
req.body.data._id = newObjectId;
try {
const response = await UserDatabase.findOneAndUpdate(
{ _id: req.body.user_id },
{
$push: {
// cardsArray: req.body.data,
cardsArray: { $each: [req.body.data] },
},
},
{ returnOriginal: false }
);
res.status(200).send(response);
} catch (error) {
console.log(error)
res.status(404).json({ message: error.message });
}
},
// edit card controller.js
editCard: async (req, res) => {
const id = req.params.id;
const { category, title, cardHolder, cardNumber, expiry, cvv, logoIndex, isFavourite } = req.body;
console.log(req.params.id)
try {
const response = await UserDatabase.findOneAndUpdate(
{ _id: "63b43ab32fc8d3c100cafecc", 'cardsArray._id': "63b709fc69a1cfa6fccd645c" },
{
$set: {
"cardsArray.$.title": req.body.title,
"cardsArray.$.category": req.body.category,
"cardsArray.$.cardHolder": req.body.cardHolder,
"cardsArray.$.cardNumber": req.body.cardNumber,
"cardsArray.$.expiry": req.body.expiry,
"cardsArray.$.cvv": req.body.cvv,
"cardsArray.$.logoIndex": req.body.logoIndex,
"cardsArray.$.isFavourite": req.body.isFavourite
}
},
);
console.log(response)
res.status(201).json(response.cardsArray);
} catch (error) {
console.log(error)
res.status(404).json({ message: error.message });
}
}
it means that there is no data matching the following _id and cardsArray._id
i thinks so its fails to find the feild 'cardsArray._id',first try finding the value by just findOne
await UserDatabase.findOneAndUpdate(
{ _id: "63b43ab32fc8d3c100cafecc", 'cardsArray._id': "63b709fc69a1cfa6fccd645c" })
if your find doesn't work try below methord not sure but it may work you have to either find the id and loop through the cardsArray of use $in or $match
await UserDatabase.findOneAndUpdate(
{ _id: "63b43ab32fc8d3c100cafecc", 'cardsArray':{$in:[ {_id:"63b709fc69a1cfa6fccd645c" }]})

Pushing into Nested array in mongodb

This is my mongoose Schema
const notesSchema = mongoose.Schema({
college: {type:String},
year: {type:String},
sem: {type:String},
branch:{type:String},
subjects: [
{
subject_id:{type:String},
name:{type:String},
codename: {type:String},
notes: [
{
notes_id:{type:String},
title: {type:String},
material: [
{
material_id:{type:String},
heading:{type:String},
link: {type:String}
}
]
}
]
}
]
})
I want to insert a object into 'material' array which is inside notes array and notes is inside subjects array.
I tried many syntax, but none of them worked for me. Recently I tried this.
try {
notes.updateOne({
$and:[ {_id: '62a61949dc0f920ae99fc687'}, {'subjects.notes.notes_id':'221fad-f35c-ee2a-65b3-8531dbfcf732'}]
},
{$push:{'subjects.0.notes.$.material':
[{ material_id: "hfklahfhoabfoab", heading: "Prime", link: "wwo.prime.com" }]
}}
This is full function code:-
router.get('/populate',async (req,res)=>{
// const {data} = req.body
// const link = "www.wiki.com"
try {
notes.updateOne({
_id: '62a61949dc0f920ae99fc687',
'subjects.notes.notes_id': '221fad-f35c-ee2a-65b3-8531dbfcf732',
},
{$push:{'subjects.0.notes.$.material':
[{ material_id: "hfklahfhoabfoab", heading: "Prime", link: "wwo.prime.com" }]
}}
)
console.log("posted")
const alreadyexist = await notes.find({$and:[{"year":'3'},{"sem":'2'}]})
res.send(alreadyexist)
// console.log(updata)
} catch (error) {
console.log(error)
}
} )
This is my current Database status.
enter image description here
Try to change your code like this:
router.get('/populate', async (req, res) => {
try {
await notes.updateOne(
{
_id: '62a61949dc0f920ae99fc687',
'subjects.notes.notes_id': '221fad-f35c-ee2a-65b3-8531dbfcf732',
},
{
$push: {
'subjects.0.notes.$.material': {
material_id: 'hfklahfhoabfoab',
heading: 'Prime',
link: 'wwo.prime.com',
},
},
}
);
console.log('posted');
const alreadyexist = await notes.find({ year: '3', sem: '2' });
res.send(alreadyexist);
} catch (error) {
console.log(error);
}
});

Postgres DatabaseError [SequelizeDatabaseError]: syntax error at or near "IN"

I have end-point which is supposed to delete record from DB:
delete: async(roleId, actionId) => {
const actionrole = await ActionRoleModel.findAll({
where: {
roleId: roleId,
actionId: actionId
},
});
return await actionrole[0].destroy();
}
That [0] has to be here, because actionrole looks like [{...}].And here is the model:
'use strict';
module.exports = (sequelize, DataTypes) => {
var ActionRole = sequelize.define('actionroles', {
actionId: {
type: "UNIQUEIDENTIFIER",
field: "actionid"
},
roleId: {
type: "UNIQUEIDENTIFIER",
field: "roleid"
},
createdAt: {
field: "createdat",
type: DataTypes.DATE
},
updatedAt: {
field: "updatedat",
type: DataTypes.DATE
},
}, {});
ActionRole.associate = function(models) {
// associations can be defined here
};
ActionRole.removeAttribute('id');
return ActionRole;
};
But as an error in terminal I get
DatabaseError [SequelizeDatabaseError]: syntax error at or near "IN"
And here is SQL:
DELETE FROM "actionroles"
WHERE IN (
SELECT FROM "actionroles"
WHERE "roleid" = '53549d62-cd2a-497f-9d1c-1ee1901261ab' AND "actionid" = '6c70bf65-30fd-4640-91d0-8fbda85c4dd5'
LIMIT 1)
What's wrong? How can I fix that?
For anyone using Sequelize version 3 and above it looks like:
Model.destroy({
where: {
// conditions
}
})
So, in this case it would be look like this:
return await ActionRoleModel.destroy({
where: {
roleId: roleId,
actionId: actionId
}
});
And it works!

Return Map Row NULL

I'm trying to map a json response from mysql query, but i receive ho response: data: NULL
This is my code:
const audience = rows.map((row) => {
db.query(CountAudiences, [row.campaign], function(err, count, fields) {
if (err) throw err;
console.log('Query result: ', count[0].audience);
return {
id: row.id,
title: row.title,
campaign: row.campaign,
action: row.action,
date: row.date,
audiences: count[0].audience
}
});
});
res.json({
count: rows.length,
data: audience
})
Response:
{
"count":1,
"data":[
null
]
}
Do you know how solve this?
Thanks :)
In your code as you are placing a query, so it is a Async hit. Try this
function getResponse(){
let rows = [{ id: 1, title: 5 }, { id: 2, title: "ggg" }]
const audience = rows.map(async (row) => {
return new Promise((resolve,reject)=> {
db.query(CountAudiences, [row.campaign], function (err, count, fields) {
if (err) throw err;
console.log('Query result: ', count[0].audience);
resolve( {
id: row.id,
title: row.title,
campaign: row.campaign,
action: row.action,
date: row.date,
audiences: count[0].audience
})
})
})
});
return Promise.all(audience)
}
getResponse().then((reponseData)=>{
res.json({
count: rows.length,
data: reponseData
})

How to filter data from firebase?

BasicData {
userid:123123,
email:something#gmail.com
},
BusData {
Dropping: ....,
Boarding:......,
.....
......
},
Traveller1 {
name:....,
seatno0.....,
age:....,
},
Traveller2 {
name:....,
seatno0.....,
age:....,
},
Traveller3 {
name:....,
seatno0.....,
age:....,
},
Traveller4 {
name:....,
seatno0.....,
age:....,
}
In BookedBusdata there is table contains BasicData BusData and TravellerData. I want to access the the Data only consist of Travellers, But it may Traveller may be 2, 4 , 10 any number The Documents consist of only Map. But i want to all the data of Traveller which are in the form of Traveller1, Traveller2 whatever Traveller are there
var docRef = db.collection("BookedTicketData").doc(orderid);
docRef.get().then(function(doc) {
if (doc.exists) {
data = doc.data()
console.log(data.Traveller1.Age) // I am getting the data if i am accessing only one
} else {
// console.log("No such document!");
}
}).catch(function(error) {
console.log("Error getting document:", error);
});
This code i have performed
If you're happy to filter the data client side, it's a fairly straight forward task
const data = {
BasicData: {},
BusData: {},
Traveller1: {
name: 'Name1',
email: 'Email1'
},
Traveller2: {
name: 'Name2',
email: 'Email2'
},
Traveller3: {
name: 'Name2',
email: 'Email2'
},
}
// returns an array of travelers
console.log(Object.keys(data).reduce((acc, key) => {
if (key.includes('Traveller')) {
acc.push(data[key])
}
return acc;
}, []))
// returns an object of travelers
console.log(Object.keys(data).reduce((acc, key) => {
if (key.includes('Traveller')) {
acc[key] = data[key];
}
return acc;
}, {}))
In your case you can just use Object.keys(doc.data()).reduce...

Categories