Update a nested array in a nested array - javascript

I am trying to update using this route.
router.put("/:id", async(req,res)=>{
try {
const updateUser = await User.findByIdAndUpdate(req.params.id, {
$push: {
clients:{
client_name: req.body.client_name,
client_Username: req.body.client_Username,
client_Password: req.body.client_Password,
documents : [
{
name : req.body.docName,
descritption : req.body.docDescription,
doc_upload : req.body.doc_upload,
}
]
}
}
},{new:true})
res.status(200).json(updateUser);
}
catch(err) {
res.status(500).json(err);
}
});
Once the function founds the id it updates client_name, client_Username and client_password without any issue.
My problem is when I try to update the nested array documents with a name/description and doc_upload. I am not able to do that.
What’s wrong ? How to do it please ?

One solution could be to separate the updates:
router.put('/:id', async (req, res) => {
try {
const { id } = req.params;
const { client_name, client_Username, client_Password } = req.body;
const updateUser = await User.findByIdAndUpdate(
id,
{
$push: {
clients: {
client_name,
client_Username,
client_Password,
},
},
},
{ new: true }
);
await User.findOneAndUpdate(
{
id,
'clients.client_name': client_name,
'clients.client_Username': client_Username,
},
{
$push: {
'clients.$.documents': {
name: req.body.docName,
descritption: req.body.docDescription,
doc_upload: req.body.doc_upload,
},
},
}
);
res.status(200).json(updateUser);
} catch (err) {
res.status(500).json(err);
}
});

Related

cant add products to shopping cart in mongodb

I am working on a shopping cart and am able to create one in mongodb but I can't add the products that are stored in the DB to the cart. It will just show an empty items array in the console.log as well as mongodb gui. Any help is appreciated.
const express = require('express');
const Carts = require('../repo/carts');
const router = express.Router();
router.post('/cart/products', async (req, res) => {
Carts.findById(req.session.cartId, (err, foundCart) => {
if(err) {
console.log(err)
}
if (foundCart) {
console.log(foundCart);
Carts.update( { _id:req.session.cartId }, {
$push: {
items: {
_id: req.body.productId,
quantity: 1,
},
},
});
} else {
if (!foundCart) {
const newCart = new Carts({
_id: req.session.cartId,
items: [],
});
newCart.save();
}
}
});
res.send('product added to cart!!');
});
module.exports = router;
carts schema for mongodb
const mongoose = require('mongoose');
const cartSchema = new mongoose.Schema({
_id: String,
items: [
{ quantity: Number, _id: String,}
]
});
const Carts = new mongoose.model('Carts', cartSchema);
module.exports = Carts;
image of cart in mongodb robo3t
That err is for the findById, you can add a similar function for the update function and see why it is not working.
Also check if the id body id is received ok.
Carts.findById(req.session.cartId, (err, foundCart) => {
if(err) {
console.log(err) // This err is for the find by Id, not to the update function
}
if (foundCart) {
console.log(foundCart)
console.log(req.body.productId)
Carts.update(
{ _id:foundCart._id }, {
$push: {
items: {
_id: req.body.productId,
quantity: 1,
},
},
},(err,updatedCart) => {
if(err){
console.log(err)
}
}
);
} else {
if (!foundCart) {
const newCart = new Carts({
_id: req.session.cartId,
items: [],
});
newCart.save();
}
}
});
res.send('product added to cart!!');
});
module.exports = router;

edit the last inserted record in mongodb

I am inserting two different objects into the db, i am doing this according to a certain criteria.
After that i am editing this record and setting the status to verified or not verified according to an amazon reply.
The problem is , i want to update the record that has been just inserted , since i am using findOneAndUpdate, only one record is being edited and it is not the last one it is the first.
Since the user can do as many purchases as he wants , he can have as many records as he want but only the first object found in the db having the userId sent as a param is edited.
what shall i use? the date and time when the object is inserted or what ?
async createAndSendToAmazon(data) {
try {
const records = new this.model(data);
const purchaseFromAppObjectRecord = await records.save();
let userId = purchaseFromAppObjectRecord.UserData[0].userId;
let receiptId = purchaseFromAppObjectRecord.receiptId;
await sendToAmazon(userId, receiptId);
await changeStatusToVerified(userId);
return purchaseFromAppObjectRecord;
} catch (error) {
return error;
}
}
}
async function sendToAmazon(userId, receiptId) {
const requestUrl = `https://appstore-sdk.amazon.com/version/1.0/verifyReceiptId/developer/2:smXBjZkWCxDMSBvQ8HBGsUS1PK3jvVc8tuTjLNfPHfYAga6WaDzXJPoWpfemXaHg:iEzHzPjJ-XwRdZ4b4e7Hxw==/user/${userId}/receiptId/${receiptId}`;
console.log(requestUrl);
fetch(requestUrl).then(function (response) {
if (response.status === 200) {
console.log(response.status);
response.json().then(async function (data) {
AmazonResolver.create(data);
});
} else {
try {
changeStatusToNotVerified(userId);
console.log(response.status);
response.json();
console.log("err will not add amazon verification object");
} catch (err) {
console.log(err);
}
}
});
}
async function changeStatusToVerified(userId) {
try {
await purchaseFromAppObjectModel.findOneAndUpdate(
{
UserData: { $elemMatch: { userId: userId } },
},
{ $set: { status: "verified" } }
);
} catch (err) {
console.log(err);
}
}
I want to write down my question as a minimal one but i want you to see my functions.
// you can use sort aggregate function to sort users in desc order and update the last element first
async function changeStatusToVerified(userId) {
try {
await purchaseFromAppObjectModel.findOneAndUpdate(
{
UserData: { $elemMatch: { userId: userId } },
},
{ $set: { status: "verified" } },
{ sort: { userId: -1 }, upsert: true, returnNewDocument: true }
);
} catch (err) {
console.log(err);
}
}
OR
async function changeStatusToVerified(userId) {
try {
await purchaseFromAppObjectModel.findOneAndUpdate(
{
UserData: { $elemMatch: { userId: userId } },
},
{ $set: { status: "verified" } },
{ sort: { userId: -1 } }
);
} catch (err) {
console.log(err);
}
}
if any one passes by here later on , this worked for me :
.findOneAndUpdate(
{
UserData: { $elemMatch: { userId: userId } },
},
{ $set: { status: "verified" }, limit: 1 }
)
.sort({ $natural: -1 });

Iterating upon Variable From Database Entry using Mongoose

I'm trying to set it up so that every time the API query entry in the database it iterates 1 to a value named Popularity, contained inside of that entry.
I have set it up so that it finds the entry then gets ready to edit the Popularity value. Is this the right approach?
router.get("/:ItemID", async (req, res) => {
try {
const updateditem = await Items.findOneAndUpdate(
{ ItemID: req.params.ItemID },
{
$set: {
Popularity: //Previous Value of POPULARITY + 1
}
}
);
res.json(updateditem);
} catch (err) {
console.log(err);
}
});
After Creating your Schema, you just have to update your model in every API hit by using mongoose inc Query
Items.findOneAndUpdate(
{ ItemID: req.params.ItemID },
{ $inc: { Popularity: 1 } },
{ new: true },
function(err, response) {
if (err) {
callback(err);
} else {
callback(response);
}
}
);
or in your code:
router.get("/:ItemID", async (req, res) => {
try {
const updateditem = await Items.findOneAndUpdate(
{ ItemID: req.params.ItemID },
{ $inc: { Popularity: 1 } },
{ new: true },
);
res.json(updateditem);
} catch (err) {
console.log(err);
}
});

Sequelize MySQL update value copy from other table

I'm trying to make a controller that will do something like this:
UPDATE bankapplication_accounts
SET last_successful_logged = last_present_logged
WHERE id = 1
My controller in sequelize looks like this:
exports.updateLastLoggedDate = (req, res) => {
User.findOne({
where: {
id: req.params.userId,
},
}).then(user => {
if (user) {
User.update(
{
last_successfull_logged: user.last_present_logged,
},
{ where: { id: req.params.userId } },
).then(() => {
res.status(200).send('logout correct');
});
}
});
};
Can this controller write better?
There are 2 ways
1:
exports.updateLastLoggedDate = (req, res) => {
User.findOne({
where: {
id: req.params.userId,
},
}).then((user) => {
if (user) {
user.update({
last_successfull_logged: user.last_present_logged,
}).then(() => {
res.status(200).send("logout correct");
});
}
});
};
2:
User.update(
{
last_successfull_logged: user.last_present_logged,
}, /* set attributes' value */
{
where: {
id: req.params.userId,
},
}, /* where criteria */
).then(() => {
res.status(200).send("logout correct");
});

How to return only value of a field in mongodb using node js.

When I queried my mongodb database with this method:
app.get('/', function (req, res) {
user.find({}, {twitter: 0, _id: 0, __v:0,}, function (err, result) {
if (err) throw err;
console.log(result);
res.render('pages/index', {
path: result
});
});
});
I got this result in return:
{ meme: { imgs: 'http://localhost/public/Images/okro.jpg' } }
{ meme: { imgs: 'http://localhost/public/Images/1518530337363-okro.jpg' } }
{ meme: { imgs: 'http://localhost/public/Images/1518530481130-meme.jpg' } }
But what I wanted it to return the actual value in the imgs field.
I want something like this.
{'http://localhost/public/Images/okro.jpg'}
{'http://localhost/public/Images/1518530337363-okro.jpg'}
{ 'http://localhost/public/Images/1518530481130-meme.jpg' }
How is this possible in MongoDB using node js?
If you don't need duplicate values, you can use distinct
db.collection.distinct('meme.imgs')
var mongoose = require('mongoose');
var Schema = mongoose.Types.ObjectId;
var condition1 = { $match: { 'twitter': { $eq: 0 } } };
var condition2 = { $match: { '_id': { $eq: 0 } } };
var condition3 = { $match: { '_id': { $eq: Schema('11111111111111111') } } };
var condition4 = { $match: { '__v': { $eq: 0 } } };
var project = { "$project": {
"imgs": '$meme.imgs'
}
};
user.find({}, {condition1,condition2,condition3,condition4,project}, function (err, result) {
})
You can simply parse the result.Updated Answer.
user.find({},{_id: 0,details:0,name:0 },function(err, docs){
docs.forEach(function(u) {
u=JSON.parse(JSON.stringify(u))
console.log(u.meme);
});
});

Categories

Resources