const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/mongo-games')
.then(() => console.log('Now connected to MongoDB!'))
.catch(err => console.error('Something went wrong', err));
const gameSchema = new mongoose.Schema({
title: String,
publisher: String,
tags: [String],
date: {
type: Date,
default: Date.now
},
onSale: Boolean,
price: Number
});
const Game = mongoose.model('Game', gameSchema);
async function saveGame() {
const game = new Game({
title: "The Legend of Zelda: Breath of the Wild",
publisher: "Nintendo",
tags: ["adventure", "action"],
onSale: false,
price: 59.99,
});
const result = await game.save();
console.log(result);
}
saveGame();
My doubt about the code is that : how in this code async/await function is used. What is use of that. Can we not make this without using them.
SOurce : https://vegibit.com/mongoose-crud-tutorial/
Related
I have a question about axios POST and GET requests.
I am working on a Next.js project to build an online store and I am using headless wordpress. The store-system I am using is called WooCommerce.
On the first page I make a POST request, which adds an order to my WooCommerce API. Basically, my POST request just adds an entry to the JSON-object.
On the next page I try to retrieve ALL my orders, but unfortunately the order that was just placed is not (always) on the list… Sometimes after reloading, it updated to the correct one. When I check at the API, all my orders are listed. I have already spend two weeks figuring out what I am doing wrong. I would be very grateful, if somebody could help me with this one.
Thank you very much in advance.
so here I have the relevant code at the checkout page (first page):
const buyNowButton = async (e) => {
...
const variation_id = JSON.parse(sessionStorage.getItem('dwgOrpdf'));
// console.log('variation_id', variation_id[0].variationID);
const line_items = valuesServer.map((item) => {
return {
product_id: item.feature.properties.main_id,
variation_id: variation_id[0].variationID, //item.feature.properties.dwg_id, austasch mit pdf oder dwg id
quantity: 1,
total: '0.00',
};
});
// console.log('lineItems', line_items);
let orderData = {
payment_method: 'bacs',
payment_method_title: 'Direct Bank Transfer',
set_paid: true,
billing: {
first_name: 'John',
last_name: 'Doe',
company: 'example',
address_1: 'example',
address_2: 'example',
city: 'example',
state: 'example',
postcode: '123456',
country: 'example',
email: membemail,
phone: '12345678',
},
shipping: {
first_name: 'John',
last_name: 'Doe',
company: 'example',
address_1: 'example',
address_2: 'example',
city: 'example',
state: 'example',
postcode: '123456',
country: 'example',
phone: '12345678',
},
// these are the products sent to the order
line_items: line_items,
shipping_lines: [
{
method_id: 'flat_rate',
method_title: 'Flat Rate',
total: '0.00',
},
],
};
axios
.post(
`webpageurl/wp-json/wc/v3/orders?consumer_key=${wcConsumerKey}&consumer_secret=${wcConsumerSecret}`,
orderData
.then((response) => {
setMembEmail('');
return response;
})
.catch((err) => {
// console.log('AXIOS ERROR processOrder: ', err);
// setOrderError(err);
});
};
And then on the next page I'll send some GET-requests to receive the data:
export default function Home({
headermenusp,
titlesp,
faviconsp,
logoimagesp,
footermenu,
page,
PageUpdate,
lastOrderLineItems,
}) {...};
return(
<>
...
</>
);
export async function getServerSideProps({ req, res }) {
const cookies = new Cookies(req, res);
let latestEmail = cookies.get('email');
...
const { data: orderID } = await axios.get(
`webpageurl/wp-json/wc/v3/orders/?search=${latestEmail}&consumer_key=${wcConsumerKey}&
consumer_secret=${wcConsumerSecret}`
);
const orderIds = orderID.map((item) => item.id);
console.log('orderIds', orderIds);
...
return {
props: { //I return a bunch of other props here...
page,
headermenusp,
footermenu,
titlesp,
postssp,
logoimagesp,
PageUpdate,
lastOrderLineItems,
},
};
}
Now this last console.log only returns all orders exept the last one.
If I refresh the page, it loads all!
Error: Objects are not valid as a React child (found: object with keys {_id, name}). If you meant to render a collection of children, use an array instead.
Tried to fix this for days and no result.
i have a model
import mongoose from 'mongoose'
const CategoriesSchema = new mongoose.Schema({
name: {
type: String,
required: true,
trim: true
},
parent: {
type: mongoose.Types.ObjectId,
ref: 'categories'
},
},
{
timestamps: true
})
let Dataset = mongoose.models.categories || mongoose.model('categories', CategoriesSchema)
export default Dataset
and i have getCategories like this
[getCategories ]
const getCategories = async (req, res) => {
try {
const categories = await Categories.find().populate("parent", "name");
res.json({ categories });
}
catch (err)
{
return res.status(500).json({ err: err.message });
}
};
in my Globale state i have
export const DataContext = createContext()
export const DataProvider = ({children}) => {
const initialState = {
notify: {}, auth: {}, cart: [], modal: [], orders: [], users: [], categories: []
}
const [state, dispatch] = useReducer(reducers, initialState)
useEffect(() => {
getData('categories').then(res => {
if(res.err)
return dispatch({type: 'NOTIFY', payload: {error: res.err}})
dispatch({ type: 'ADD_CATEGORIES', payload: res.categories })
})
},[])
return(
<DataContext.Provider value={{state, dispatch}}>
{children}
</DataContext.Provider>
)
}
when i call categories throw:exception
when i change dispatch in Globale state like :
dispatch({ type: 'ADD_CATEGORIES', payload: [] })
i get no elements in array :
I have a simple function that register users in firebase and save data in cloud firestore
But I am getting this error:
[TypeError: Cannot call a class as a function]
Can anyone help my find where is located the error?
function below:
const handleSignUp = useCallback(
async data => {
try {
setLoading(true);
const auth = await authFB().createUserWithEmailAndPassword(
data.email,
data.password,
);
const db = firestore();
const firstName = data.name.split(' ').slice(0, -1).join(' ');
const lastName = data.name.split(' ').slice(-1).join(' ');
await db
.collection('Providers')
.doc(auth.user.uid)
.set({
id: auth.user.uid,
name: {
first: firstName,
last: lastName,
},
email: data.email,
createdAt: firestore.Timestamp.fromDate(new Date()),
address: {
position: firestore.GeoPoint(
coordinates.latitude,
coordinates.longitude,
),
},
})
.then(() => {
navigation.reset({
routes: [{ name: 'SignIn' }],
index: 0,
});
});
setLoading(false);
Alert.alert(
'Cadastro realizado com sucesso!',
'Você já pode fazer login na aplicação.',
);
} catch (err) {
setLoading(false);
}
},
[coordinates],
);
I'm not terribly familiar with the Firestore API, but most likely you just need the new keyword where you're creating a GeoPoint:
position: new firestore.GeoPoint(
coordinates.latitude,
coordinates.longitude,
),
I'm wondering if there is a pattern that allows you to use action creators inside of other action creators. The modifyMassProperty action creator lets you pass any number of actions which are then iterated over and dispatched accordingly. I would very much like to be able to use this method in the getOrbitalBurn action creator since it would be semantically more appealing than using the dispatch method made available by the thunk three times in a row. I'm confident I must either have missed something, or that I'm guilty of getting tangled up in some sort of anti pattern that I concocted during one of my lesser days.
export const modifyMassProperty = (
...massProperties: MassProperty[]
): ThunkAction<void, AppState, void, Action> => (
dispatch: Dispatch<ScenarioActionTypes>
) =>
massProperties.forEach(massProperty =>
dispatch({
type: MODIFY_MASS_PROPERTY,
payload: massProperty
})
);
export const getOrbitalBurn = (
payload: { primary: string; periapsis: number; apoapsis: number },
applyBurn = true
): ThunkAction<void, AppState, void, Action> => (
dispatch: Dispatch<ScenarioActionTypes>,
getState: any
) => {
const scenario = getState().scenario;
const primary = getObjFromArrByKeyValuePair(
scenario.masses,
'name',
payload.primary
);
const orbit = orbitalInsertion(primary, payload, scenario.g);
if (applyBurn) {
const [spacecraft] = scenario.masses;
dispatch({
type: MODIFY_MASS_PROPERTY,
payload: {
name: spacecraft.name,
key: 'vx',
value: orbit.x
}
});
dispatch({
type: MODIFY_MASS_PROPERTY,
payload: {
name: spacecraft.name,
key: 'vy',
value: orbit.y
}
});
dispatch({
type: MODIFY_MASS_PROPERTY,
payload: {
name: spacecraft.name,
key: 'vz',
value: orbit.z
}
});
}
dispatch({
type: MODIFY_SCENARIO_PROPERTY,
payload: {
key: 'orbitalInsertionV',
value: { x: orbit.x, y: orbit.y, z: orbit.z }
}
});
};
Firstly, I'm working with React Native. I'm getting a data from Firebase and want to write to store (by Redux) quickly. But It doesn't work. You can find my all of codes below:
Function:
async getTumData (uid) {
const {selectedGroupDetail, getSelectedGroupDetail} = this.props;
var yeniGrupDetayi = {};
await firebase.database().ref("/groups/"+uid).once('value').then(
function(snapshot){
yeniGrupDetayi = {...snapshot.val(), uid: uid};
}).catch(e => console.log(e.message));
console.log("FONKSIYON ICERISINDEKI ITEM ==>", yeniGrupDetayi);
this.props.getSelectedGroupDetail(yeniGrupDetayi);
console.log("ACTION'DAN GELEN ITEM ===>", selectedGroupDetail);
}
Action:
export const getSelectedGroupDetail = (yeniGrupDetayi) => {
return {
type: GET_SELECTED_GROUP_DETAIL,
payload: yeniGrupDetayi
}
};
Reducer:
case GET_SELECTED_GROUP_DETAIL:
return { ...state, selectedGroupDetail: action.payload}
Çıktı:
FONKSIYON ICERISINDEKI ITEM ==> {admin: {…}, groupDescription: "Yaygın inancın tersine, Lorem Ipsum rastgele sözcü…erini incelediğinde kesin bir kaynağa ulaşmıştır.", groupName: "İnsan Kaynakları", groupProfilePic: "", members: {…}, …}
ACTION'DAN GELEN ITEM ===> {}
There is a FlatList in my page and I defined a button in renderItem of FlatList. When i click to this button, getTumData() function is working.
When i click to this button first time, selectedGroupDetail is null. Second time, it shows previous data.
How can i write a data to Store quickly and fast?
Thanks,
The thing is:
- You're using both async/await, and then/catch in your code.
- you're calling getSelectedGroupDetail before your async code resolves.
Fast Solution
getTumData = (uid) => {
const {selectedGroupDetail, getSelectedGroupDetail} = this.props;
var yeniGrupDetayi = {};
firebase.database().ref("/groups/"+uid).once('value').then(
(snapshot) => {
yeniGrupDetayi = {...snapshot.val(), uid: uid};
this.props.getSelectedGroupDetail(yeniGrupDetayi);
}).catch(e => console.log(e.message));
};
Better Solution:
1st: use Redux-Thunk middleware.
2nd: Move your Async code into your action creator: I mean this
async getTumData (uid) {
const {selectedGroupDetail, getSelectedGroupDetail} = this.props;
var yeniGrupDetayi = {};
await firebase.database().ref("/groups/"+uid).once('value').then(
function(snapshot){
yeniGrupDetayi = {...snapshot.val(), uid: uid};
}).catch(e => console.log(e.message));
console.log("FONKSIYON ICERISINDEKI ITEM ==>", yeniGrupDetayi);
this.props.getSelectedGroupDetail(yeniGrupDetayi);
console.log("ACTION'DAN GELEN ITEM ===>", selectedGroupDetail);
}
3rd: Your reducer should have another piece of data as an indicator for the time-gap before your selectedGroupDetail resolves:
// reducer initial state:
const INITIAL_STATE = { error: '', loading: false, selectedGroupDetail: null }
4th: Inside your action creator, you should dispatch 3 actions:
ACTION_NAME_START // This should should only set loading to true in your reducer.
ACTION_NAME_SUCCESS // set loading to false, and selectedGroupDetail to the new collection retured
ACTION_NAME_FAIL // in case op failed set error
5th: Your React component, should display a loading indicator (spinner or somthing), and maybe disable FlatList button during the loading state.
// Action creator
export const myAction = () => (dispatch) => {
dispatch({ type: ACTION_NAME_START });
firebase.database().ref("/groups/"+uid).once('value').then(
function(snapshot){
yeniGrupDetayi = {...snapshot.val(), uid: uid};
dispatch({ type: ACTION_NAME_SUCCESS, payload: yeniGrupDetayi });
}).catch(e => {
dispatch({ type: ACTION_NAME_FAIL, payload: e.message });
});
};
// Reducer
const INITIAL_STATE = {
loading: false,
error: '',
data: null,
};
export default (state = INITIAL_STATE, { type, payload }) => {
switch (type) {
case ACTION_NAME_START:
return {
...state,
error: '',
loading: true,
data: null,
};
case ACTION_NAME_SUCCESS:
return {
...state,
error: '',
loading: false,
data: payload,
};
case ACTION_NAME_FAIL:
return {
...state,
error: payload,
loading: false,
data: null,
};
default:
return state;
}
};