Update Controller
exports.UpdatePanelMembers = (req, res) => {
const { panelId } = req.params;
if (panelId) {
Panel.findOneAndUpdate(
{ _id: panelId },
{
panelMembers: {
member1: {
memberId: req.body.panelMembers.member1.memberId,
fullName: req.body.panelMembers.member1.fullName,
username: req.body.panelMembers.member1.username,
},
member2: {
memberId: req.body.panelMembers.member2.memberId,
fullName: req.body.panelMembers.member2.fullName,
username: req.body.panelMembers.member2.username,
},
member3: {
memberId: req.body.panelMembers.member3.memberId,
fullName: req.body.panelMembers.member3.fullName,
username: req.body.panelMembers.member3.username,
},
},
}
).exec((error, result) => {
if (error) return res.status(400).json({ error });
if (result) {
res.status(202).json({ result });
}
});
}
};
In this code, if I update member1 details only, other data will be erased. So I want to update only relevant data like this postman JSON.
Postman JSON Code
{
"panelMembers": {
"member1": {
"username":"john.j",
"fullName":"John Jade",
"memberId":"member123"
}
}
}
Postman
Frontend is like this
You just have to update member1 in panelMembers object. So for that, send member1 object in request from postman and make your query as :-
Panel.findOneAndUpdate({ _id: panelId },{'panelMembers.$.member1': member1})
This will only update member1 object. Other objects will not be affected or erased.
Related
I'm trying to do a query based on some data but apparently, $nin is not reading the returned values from the function.
My goal is to not show all the users I've followed on the recommended section where there is a get request to receive all the users registered on the db.
I do have the following users on the function, however when I try to do the query, its not working and I've tried for hours fixing that problem.
At username: { $nin: [allFollowers.forEach((following) => following.username)] => Doing this, doesnt work, however when I put strings from the list of following users such as 'user1', 'user2', it works. My api updates on the client and I dont see those two users I follow on the recommended section.
I'd appreciate if you could help me.
exports.recommendedUsers = async function (req, res) {
// all following users in an array
const { followingUsers } = req.body;
/* console.log(followingUsers) =>
[
{
username: 'user1',
avatar: '//www.gravatar.com/avatar/c76fa83b3saddasdas2c04a59d6e063918badbf53?s=200&r=pg&d=mm'
},
{
username: 'user2',
avatar: '//www.gravatar.com/avatar/3758e369b058b393541asdasda4d0e8a1d57402?s=200&r=pg&d=mm'
},
{
username: 'uiser3',
avatar: 'https://static-cdn.jtvnw.net/jtv_user_pictures/bobross-profile_image-0b9dd16cascad7a9bb16b5-70x70.jpeg'
},
{
username: 'user4',
avatar: 'https://static-cdn.jtvnw.net/jtv_user_pictures/82b63a01-628f-4c81-9b05-dd3a501asdasd1fdda-profile_image-70x70.png'
},
{
username: 'user5',
avatar: '//www.gravatar.com/avatar/93cd495a412a1b2asdadabe9b9c72bc246e271?s=200&r=pg&d=mm'
}
] */
let allFollowers = [];
let following = req.body.followingUsers.forEach((follow) =>
allFollowers.push(JSON.stringify(follow.username))
);
console.log(`this is all followers: ${allFollowers}`);
try {
const user = User.find(
{
_id: { $ne: req.user.id },
username: {
$nin: [allFollowers.forEach((following) => following.username)], // not working
},
},
function (err, users) {
let userMap = {};
users.forEach(function (user) {
userMap[user._id] = user;
});
const arrayData = Object.values(userMap);
return res.json(arrayData);
}
).select('-password');
} catch (e) {
console.log(e.message);
}
};
You are using foreach function, that is wrong:
username: {
$nin: [allFollowers.forEach((following) => following.username)],
}
The return value of foreach is undefined, use map function.
try {
const user = User.find(
{
_id: { $ne: req.user.id },
username: {
$nin: allFollowers.map((following) => following.username),
},
},
function (err, users) {
let userMap = {};
users.forEach(function (user) {
userMap[user._id] = user;
});
const arrayData = Object.values(userMap);
return res.json(arrayData);
}
).select('-password');
} catch (e) {
console.log(e.message);
}
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 });
I would like to use users.findOne method using two params like in the example below, not just with the id or name but with both
const user = await Tags.findOne({
where: { id: ID, name: NAME },
});
As far as I know you code should work, but you can try the following approach:
const user = await Tags.findAll({
where: {
[Op.and]: [
{ id: ID },
{ name: NAME }
]
}
});
You can define operators for the where clause manually. For reference see https://sequelize.org/master/manual/model-querying-basics.html#applying-where-clauses
here is an example . you have to user the Op from sequelize.
const { Op } = require("sequelize");
const isFoundNumber = await db.users.findOne({
where: {
[Op.or]: [
{
mobile_number: params.mobile_number,
},
{ email: params.email },
],
},
});
if (isFoundNumber != null) {
let user = basicDetails(isFoundNumber);
if (params.mobile_number == user.mobile_number) {
reject({
status: false,
errorMessage: `Mobile Number ${params.mobile_number} already regstered`,
data: basicDetails(isFoundNumber),
});
}
if (params.email === user.email) {
reject({
status: false,
errorMessage: `Email Account ${params.email} already regstered`,
data: user,
});
}
}
So I am having event object, which have comments, and comments have likes array.
What I currently can do is to add like to comments array of event object.
My schema looks similar to this:
creator: {
type: Schema.Types.ObjectId,
ref: 'User'
},
comments: [
{
user: {
type: Schema.Types.ObjectId,
ref: 'User'
},
text: {
type: String,
required: true
},
likes: [
{
user: {
type: Schema.Types.ObjectId,
ref: 'User'
}
}
]
}
]
}
And my current add like to comments function looks like this:
commentLike: async (req, res) => {
console.log('working', req.params.id, req.params.idas, req.params.commentID);
Events.findOneAndUpdate(
{ _id: req.params.idas, comments: { $elemMatch: { _id: req.params.commentID } } },
{ $push: { 'comments.$.likes': { user: req.params.id } } },
(result) => {
res.json(result);
}
);
}
Params: idas- event._id, commentID: comment id, id: user._id
The problem is that i can add endless likes since, I have no logical operation to check if user already liked it, and im really strugling, in this findoneandupdate function to do that. But thats on problem, another thing what I want to do is unlike comment, and Im having atrouble at figuring it out, on how to get user index from likes array so i can slice that index out, currently my function is looking like this:
deleteLike: async (req, res) => {
console.log('working', req.params.id, req.params.idas, req.params.commentID);
Events.findOneAndUpdate(
{ _id: req.params.idas, comments: { $elemMatch: { _id: req.params.commentID } } },
{
$push: {
'comments.$.likes': {
$each: [],
$slice: 0 //there instead of 0 should be user index
}
}
},
(result) => {
res.json(result);
}
);
}
On this function im also using findoneandupdate function, which is probably not a good idea? Was trying to use findandremove, but it removes entire event object.
So i managed to to it, by using pull operator.
Working delete comment like fuction
deleteLike: async (req, res) => {
console.log('working', req.params.id, req.params.idas, req.params.commentID);
Events.findOneAndUpdate(
{ _id: req.params.idas, comments: { $elemMatch: { _id: req.params.commentID } } },
{
$pull: { 'comments.$.likes': { user: req.params.id } }
},
(result) => {
res.json(result);
}
);
}
};
I do not know why I unable to retrieve user id when creating a new account and add a role for this user.
methods.js :methods for update and insert new account driver with which I would assign the roles 'driver' for every new account ,registering a new account is going successfully, but the addition of a role does not work
import { Meteor } from 'meteor/meteor';
import { Accounts } from 'meteor/accounts-base';
import { CONST } from '../../common/constants.js';
import { Roles } from 'meteor/alanning:roles';
Meteor.methods({
updateUserProfile: (newProfile) => {
const userId = Meteor.userId();
// var isEmailChanged = currentProfile ?
// newProfile.email != currentProfile.email :
Meteor.users.update(userId, {
$set: {
profile: newProfile,
},
}, {
validationContext: 'updateUserProfile',
});
},
createDriver: (newUser) => {
var id =Accounts.createUser({
username: newUser.username,
email: newUser.email,
password: newUser.password,
profile: newUser.profile,
roles: CONST.USER_ROLES.DRIVER,
});
//console.log(Meteor.userId());
Roles.addUsersToRoles(id, roles);
},
});
Driver-join.js
Meteor.call('createDriver', data, (error) => {
if (error) {
Session.set(SESSION.ERROR, error);
} else {
FlowRouter.go('/s/driver/vehicles'); // TODO : replace with redirection by root name
}
});
roles
roles: {
type: [String],
optional: true,
allowedValues: [CONST.USER_ROLES.CLIENT, CONST.USER_ROLES.DRIVER, CONST.USER_ROLES.ADMIN],
defaultValue: CONST.USER_ROLES.CLIENT,
},
What if add this to the server?
Meteor.users.after.insert(function (userId, doc) {
Roles.addUsersToRoles(doc._id, [CONST.USER_ROLES.DRIVER])
});
Also remove roles property when you add new user, it doesn't work.
But your code should work as well. What is the roles in Roles.addUsersToRoles(id, roles);?