I'm having some issues using the addRole property.
Here is my code:
let role = client.guilds.get(targetserver).createRole({ name: "OP", permissions: [8] , color: "#ff0000"});
let rolefind = client.guilds.get(targetserver).roles.find("name", "OP")
client.guilds.get(targetserver).members.get(urid).addRole(rolefind)
You have to use:
let role = await client.guilds.get(targetserver).createRole({ name: "OP", permissions: [8], color: "#ff0000"});
With await because guild.createRole is a function that returns a promise.
Related
I am making a warning system within discord.py and I got the actual data to write with the info I need, but when I run the command again it only replaces the data in the original object/warn. The point is that each warn is considered an object in the array, but it doesn't add another object for the new warn
#commands.command()
#commands.guild_only()
# #commands.has_guild_permissions(kick_members=True)
async def warn(self, ctx, user: discord.User, *, reason=None):
if user is None:
await ctx.send("You have not provided a user!")
return
if user is user.bot:
await ctx.send(f"<#{ctx.author.id}, you cannot warn a bot!")
return
if user.id == ctx.author.id:
embed = discord.Embed(description=f"<#{ctx.author.id}>, you are not allowed to warn yourself!")
embed.set_author(name=ctx.author.display_name, icon_url=ctx.author.avatar_url)
embed.set_footer(text=f"{ctx.message.guild.name} Custom Designed Bot")
embed.timestamp = ctx.message.created_at
await ctx.send(embed=embed)
return
reason = reason or None
_id = await self.bot.warns.find_by_id({"_id": user.id})
first_warning = True
warn = {
"_id": user.id,
"guild": ctx.message.guild.id,
"warn": [{
"PunishType": 'warn',
"Moderator": ctx.message.author.id,
"Reason": reason,
}]
}
if first_warning:
embed = discord.Embed(description=f"<#{ctx.author.id}>, has warned <#{user.id}> for {reason}")
embed.set_author(name=ctx.author.display_name, icon_url=ctx.author.avatar_url)
embed.timestamp = ctx.message.created_at
await ctx.send(embed=embed)
await self.bot.warns.upsert(warn)
return first_warning is False
elif first_warning is False:
warns = await self.bot.warns.find_by_id({"_id": user.id})["warns"]
newwarn = [{
"PunishType": "warn",
"Moderator": ctx.author.id,
"Reason": reason,
}]
warns.append(newwarn)
await self.bot.warns.update(
{"_id": "user.id"},
{"$push": {"warns": warns}})
If you have an array with pymongo.
You must get the database object like await self.bot.warns.find_by_id({"_id": user.id}) get the array. Do array.append(newwarn) then insteadof updating warn with newwarn you replace newwarn with the array.
warn = {
"_id": user.id,
"guild": ctx.message.guild.id,
"warns": [{
"PunishType": 'warn',
"Moderator": ctx.message.author.id,
"Reason": reason,
}]
}
await self.bot.warns.upsert(warn)
warns = await self.bot.warns.find_by_id({"_id": user.id})["warns"]
newwarn = [{
"PunishType": "warn",
"Moderator": ctx.author.id,
"Reason": reason,
}]
warns.append(newwarn)
await self.bot.warns.update(
{"_id": "user.id"},
{ "$push" : {"warns": warns}})
When I did a console.log(dbdata.user) it returned:
createdAt: "2020-11-17T04:32:17.934Z"
date: "2020-11-17T04:32:17.931Z"
displayname: "Batman"
followers: ["5fbb3879e8902d14f8c60448"]
updatedAt: "2020-12-02T14:58:17.880Z"
__v: 0
_id: "5fb35251888e8d081c06a7fa"
__proto__: Object
But when I did a console.log(dbdata.user.followers), it returned undefined. What am I missing here?
I am using useEffect and the state code:
const [dbdata,setDBData] = useState({post:[],user:[]})
useEffect(async() => {
const response = await Axios.get('http://localhost:5000/api/posts/allpost', {withCredentials:true})
setDBData(response.data)
}, [])
Many thanks in advance and greatly appreciated.
You have declared the user to be of type Array in useState Hook. While you are trying to access dbdata.user.followers which points out that the user is of type object. Try changing the console statement to below.
EDIT:
You need to flatten the followers array before searching for values. Because it's an array inside an array.
var user = [
{
'createdAt': "2020-11-17T04:32:17.934Z",
'date': "2020-11-17T04:32:17.931Z",
'displayname': "Batman",
'followers': ["5fbb3879e8902d14f8c60448"],
'updatedAt': "2020-12-02T14:58:17.880Z"
},
{
'createdAt': "2020-11-17T04:32:17.934Z",
'date': "2020-11-17T04:32:17.931Z",
'displayname': "Batman",
'followers': ["123"],
'updatedAt': "2020-12-02T14:58:17.880Z"
}
]
var followersArray = [];
user.forEach(e => followersArray.push(...e.followers))
console.log(followersArray.includes("123"))
console.log(followersArray.includes("00000"))
I basically have this route
app.post("/order/:orderId/:productId", async (req, res) => {
const result = await Order.findByIdAndUpdate(
req.params.orderId,
{
$push: {
products: req.params.productId
}
},
{ new: true }
);
res.send(result);
});
I have two collections, namely Product and Orders. The goal is to get, for instance, a particular Order with id(5ddfc649e1e9e31220ce6a16) , and post a product with id(5de02c4a0ed3160368b9a550) inside an Array field inside this Orders collection. In Postman, I can do that manually by just adding the ObjectIds in the URL like so:
Http://localhost:3000/orders/5ddfc649e1e9e31220ce6a16/5de02c4a0ed3160368b9a550.
and I get this Response :
{
"products": [
"5ddfb388b14c5b41e0607a5e",
"5de02c4a0ed3160368b9a550" // newly added Product
],
"_id": "5ddfc649e1e9e31220ce6a16",
"issuedBy": "issuedBy",
"collectedBy": "collectedBy",
"quantity": 123,
"createdAt": "2019-11-28T11:48:40.500Z",
"updatedAt": "2019-11-28T11:59:51.659Z",
"__v": 0
}
My challenge is, how do I do this programmatically from the UI(Reactjs) side?
// Product Schema
const mongoose = require("mongoose");
const ProductSchema = new mongoose.Schema(
{
name: String,
description: String,
price: Number,
quantity: Number,
supplier: String
},
{ timestamps: true }
);
module.exports = mongoose.model("Product", ProductSchema);
// Orders Schema
const mongoose = require("mongoose");
const OrderSchema = new mongoose.Schema(
{
issuedBy: String,
collectedBy: String,
quantity: Number,
products: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "Product",
required: true
}
]
},
{ timestamps: true }
);
module.exports = mongoose.model("Order", OrderSchema);
I would really appreciate any suggestion or a sample code snippet
I think what you are looking for is, you need to hit this API from your front end i.e. React app.
http://localhost:3000/orders/<order-id-here>/<product-id-here>
And then supply the dynamic value for your order id and product id.
You can hit api using fetch. More info
You can simply take some variables in your front end app. As I don't know how your order id and product id are being generated so you need to check on that and then something like,
let orderId = someValue
let productId = someOtherValue
let url = "http://localhost:3000/orders/"+orderId+"/"+productId
But I think the concern would be GET and POST method. Right now you have app.post but the params are in URL so instead you should go for GET method i.e. app.get
I am working on a project with vue.js and to handle my AJAX requests I use Axios, I wonder if it is possible to pass as a parameter to a POST request an array of objects, of this type:
[{id: 1, name: 'max'}, {id: 2, name: 'jhon'}, {id: 3, name: 'anna'}]
If possible, what is the best way to do this?
Sure!
let arrOfObj = [
{ name: 'John', lastName: 'Doe' },
{ name: 'Jane', lastName: 'Doe' }
]
axios.post('url_here',arrOfObj)
.then(console.log)
.catch(console.log)
Yes, it's very possible
let data = [
{id: 1, name: 'max'},
{id: 2, name: 'jhon'},
{id: 3, name: 'anna'}
];
let formdata = new FormData();
formdata.append('data',JSON.stringify(data));
axios.post('/url`',formdata)
.then(res => console.log(res))
.catch(err => console.log(err)
On the receiving end (assuming it's PHP & Laravel)
$data = json_decode($request->data);
then loop through $data as it's a normal array
Lema's answer was the only one that worked for me while using axios + vue + .net Core.
I was trying to send a post to my backend which was expecting an array. Following Lema's implementation I received an string and then deserialized the json string to the type I was expecting.
public IActionResult PostMethod([FromForm]string serialized_object_name){
var expectedArray = JsonConvert.DeserializeObject<ArrayTypeNeeded[]>(serialized_object_name);
}
I have spent doing such a straight forward thing. I just want to do a CRUD operation on a user model using nodejs, mongoose, restify stack. My mongo instance is on mongolab.
The user should contain a "loc" field . User schema is as follows :
var mongoose = require('mongoose')
var Schema = mongoose.Schema;
var userSchema = new Schema( {
email_id : { type: String, unique: true },
password: { type: String},
first_name: String,
last_name: String,
age: String,
phone_number: String,
profile_picture: String,
loc: {
type: {},
coordinates: [Number]
}
});
userSchema.index({loc:'2d'});
var User = mongoose.model('user', userSchema);
module.exports = User;
the rest api used to post is as follows :
create_user : function (req, res, next) {
var coords = [];
coords[0] = req.query.longitude;
coords[1] = req.query.latitude;
var user = new User(
{
email_id : req.params.email_id,
password: req.params.password,
first_name: req.params.first_name,
last_name: req.params.last_name,
age: req.params.age,
phone_number: req.params.phone_number,
profile_picture: req.params.profile_picture,
loc: {
type:"Point",
coordinates: [1.0,2.0] // hardcoded just for demo
}
}
);
user.save(function(err){
if (err) {
res.send({'error' : err});
}
res.send(user);
});
return next();
},
Now when i do a POST call on curl -X POST http://localhost:3000/user --data "email_id=sdass#dfAadsfds&last_name=dass&age=28&phone_number=123456789&profile_picture=www.jakljf.com&longitude=1.0&latitude=2.0"
I get the following error
{
error: {
code: 16804
index: 0
errmsg: "insertDocument :: caused by :: 16804 location object expected, location array not in correct format"
op: {
email_id: "sdass#dfAadsfdsadkjhfasvadsS.com"
password: "sdass123DadakjhdfsfadfSF45"
first_name: "shaun"
last_name: "dass"
age: "28"
phone_number: "123456789"
profile_picture: "www.jakljf.com"
loc: {
coordinates: [2]
0: 1
1: 2
-
type: "Point"
}-
_id: "55efc95e0e4556191cd36e5e"
__v: 0
}-
}-
}
The location field is giving problems as the POST call works just fine if i remove the loc field from model
Below are the hits/trials I did :
1) Change userSchema.index({loc:'2d'}); to userSchema.index({loc:'2dsphere'});
2) Changing loc schema to everything given in Stackoverflow. I would like to know the right way to define this though.
3) Passing the hardcode 2d array but still it says Location object expected, location array not in correct format" what format is required for this ?
Any help in this regard is greatly appreciated. Thanks.
MongoDB 2d index requires the legacy coordinates pairs format, which is just an array of coordinates like [1, 2].
If you need GeoJSON support, please use the 2dsphere index.
userSchema.index({loc:'2dsphere'});
If you are using Spring Boot make sure you set the index type to 2DSphere:
#GeoSpatialIndexed(type = GeoSpatialIndexType.GEO_2DSPHERE) GeoJsonPoint location;