how can insert scema object in mongoose expresss - express

this my model app
import mongoose, { mongo, Schema } from "mongoose";
const app = mongoose.Schema({
'name':{
type: String
},
'parent':{
type: String
},
'order':{
type:Number
},
'path':{
type: String,
},
'accesses': [
{
type: mongoose.Schema.Types.ObjectId,
ref: "Accesses"
}
]
},
{ timestamps: true },);
export default mongoose.model('Apps',app);
this my model accesses
import mongoose, { mongo } from "mongoose";
const accesses = mongoose.Schema({
'name':{
type: String,
require: true
},
'app':[{
type: mongoose.Schema.Types.ObjectId,
ref: "Apps"
}]
},
{ timestamps: true },);
export default mongoose.model('Accesses',accesses);
this my controller
export const saveApp = async (req,res) => {
try {
const app = new App(req.body);
const accesses = app.accesses;
let newAccs = [];
for (const acc of accesses)
{
const newAcc = await Accesses.findById(acc._id)
newAccs.push(newAcc);
}
app.accesses = newAccs;
const result = await app.save()
res.status(201).json(result);
} catch (error) {
res.status(400).json({message: error.message});
}
}
this my client.rest
POST http://localhost:3000/app
Content-Type: application/json
{
"name": "Ads Management testing",
"parent": "null",
"order": 1,
"path": "ads-management/",
"accesses": "63689567eee823ff6f39e969"
}
this my result
{
"name": "Ads Management testing",
"parent": "null",
"order": 1,
"path": "ads-management/",
"accesses": [
{
"app": [],
"_id": "63689567eee823ff6f39e969",
"name": "rejected",
"createdAt": "2022-11-07T05:19:35.590Z",
"updatedAt": "2022-11-07T05:19:35.590Z",
"__v": 0
}
],
"_id": "636a09d82ea451f510a56534",
"createdAt": "2022-11-08T07:48:40.035Z",
"updatedAt": "2022-11-08T07:48:40.035Z",
"__v": 0
}
my expecting data nested like this
why in my mongose accesses just put an id not all of object

Related

How to prevent to lost session after refresh in nuxt?

I am currently working on a nuxtJS app in which the session seems to be lost after any refresh (although only in dev, not while deployed). I've tried to look up in the auth module of nuxt, and have tried many answers on google, but nothing seems to work and I'm a bit lost.
nuxt.config.js
auth: {
strategies: {
local: {
scheme: 'refresh',
token: {
property: 'token',
maxAge: 3600,
global: true,
},
refreshToken: {
property: 'refresh_token',
data: 'refresh_token',
maxAge: 60 * 60 * 24 * 30,
},
user: {
property: 'user',
},
endpoints: {
login: { url: '/authentication_token', method: 'post' },
refresh: { url: '/refresh/token', method: 'post' },
logout: false,
user: { url: '/api/user', method: 'get' },
},
autoLogout: true,
},
},
},
LoginMenu.js
methods: {
async onSubmit() {
try {
const response = await this.$auth.loginWith('local', {
data: this.login,
});
if (response.status === 200) {
await this.$auth.setUser({
email: this.login.email,
password: this.login.password,
});
await this.$router.push('/');
}
else {
this.loginFail();
}
}
catch (e) {
this.loginFail();
}
},
loginFail() {
this.showError = true;
},
},
nuxt auth.js
import Middleware from './middleware'
import { Auth, authMiddleware, ExpiredAuthSessionError } from '~auth/runtime'
// Active schemes
import { RefreshScheme } from '~auth/runtime'
Middleware.auth = authMiddleware
export default function (ctx, inject) {
// Options
const options = {
"resetOnError": false,
"ignoreExceptions": false,
"scopeKey": "scope",
"rewriteRedirects": true,
"fullPathRedirect": false,
"watchLoggedIn": true,
"redirect": {
"login": "/login",
"logout": "/",
"home": "/",
"callback": "/login"
},
"vuex": {
"namespace": "auth"
},
"cookie": {
"prefix": "auth.",
"options": {
"path": "/"
}
},
"localStorage": {
"prefix": "auth."
},
"defaultStrategy": "local"
}
// Create a new Auth instance
const $auth = new Auth(ctx, options)
// Register strategies
// local
$auth.registerStrategy('local', new RefreshScheme($auth, {
"token": {
"property": "token",
"maxAge": 3600,
"global": true
},
"refreshToken": {
"property": "refresh_token",
"data": "refresh_token",
"maxAge": 2592000
},
"user": {
"property": "user"
},
"endpoints": {
"login": {
"url": "/authentication_token",
"method": "post"
},
"refresh": {
"url": "/refresh/token",
"method": "post"
},
"logout": false,
"user": {
"url": "/api/user",
"method": "get"
}
},
"autoLogout": true,
"name": "local"
}))
// Inject it to nuxt context as $auth
inject('auth', $auth)
ctx.$auth = $auth
// Initialize auth
return $auth.init().catch(error => {
if (process.client) {
// Don't console log expired auth session errors. This error is common, and expected to happen.
// The error happens whenever the user does an ssr request (reload/initial navigation) with an expired refresh
// token. We don't want to log this as an error.
if (error instanceof ExpiredAuthSessionError) {
return
}
console.error('[ERROR] [AUTH]', error)
}
})
}

Vue data fetched object not available in setup()

I am rendering a jspreadsheet component with data fetched from fastapi.
<template>
<h1>Synthèse évaluation fournisseur</h1>
<VueJSpreadsheet v-model="data.table" :options="myOption" />
{{ data.columns }}
</template>
<script>
import { reactive, onMounted, isProxy, toRaw, ref } from "vue";
import VueJSpreadsheet from "vue3_jspreadsheet";
import "vue3_jspreadsheet/dist/vue3_jspreadsheet.css";
export default {
components: {
VueJSpreadsheet,
},
setup() {
// var intervalID = setInterval(init, 3000);
var data = reactive({
table: [],
columns: [],
});
async function load_data() {
const response = await fetch("http://LOCALHOST:8080/supplier_overview");
return await response.json();
}
load_data().then((response)=>{
data.table=JSON.parse(response.result.data)
data.columns=(response.result.columns)
});
console.log(data.columns)
const myOption = ref({
columns: data.columns,
search: true,
filters: true,
includeHeadersOnDownload: true,
includeHeadersOnCopy: true,
defaultColAlign: "left",
tableOverflow: true,
tableHeight: "800px",
parseFormulas: true,
copyCompatibility: true,
});
return {
data,
myOption,
};
},
};
</script>
whereas data.columns is rendered correctly in the template, I cannot pass it to myOptions .
The proxy is empty with console.log(data.columns) whereas {{data.columns}} returns the correct array :
[ { "title": "period" }, { "title": "fournisseur" }, { "title": "Qualité" }, { "title": "Rques Qualité" }, { "title": "Logistique" }, { "title": "Rques Logistique" }, { "title": "Cout" }, { "title": "Rques Cout" }, { "title": "Système" }, { "title": "Rques Système" }, { "title": "Mot QLCS" }, { "title": "Note" }, { "title": "Rques" } ]
Any ideas why I cannot passed it correctly to myOptions ?
This problem has nothing to do with the variable myOptions
setup() {
async function load_data() {
const response = await fetch("http://LOCALHOST:8080/supplier_overview");
return await response.json();
}
//the function is async, 1 will be called after 2, so the result is empty
load_data().then((response)=>{
data.table=JSON.parse(response.result.data)
//1
data.columns=(response.result.columns)
});
//2
console.log(data.columns)
}

State object cannot re assign by payload objects in mutations

I have this state object, with default values
state() {
return {
projects: [
{ code: "01", name: "test" },
{ code: "01", name: "test" },
{ code: "01", name: "test" },
],
};
},
and I'm trying to replace it with payload that came from actions,
mutations: {
setProject(state,payload) {
state.projects = payload;
}
},
The problem is it doesn't replace the state.projects object when im trying to use console.log
i am using vuex 3.6.2 my payload is like this
[
{ code: "01", name: "Picture" },
{ code: "02", name: "Perfect" },
],
Try state being an object not a function. E.g.
const state = {
projects: [
{ code: "01", name: "test" },
{ code: "01", name: "test" },
{ code: "01", name: "test" },
],
}

How to get the correct object in an nested array in Vue.js?

I use Axios to display a JSON data and I have succeeded. But I want to show an object based on date and time, it shows now all data and I need to filter it.
So I want to look at today's date and show the object based on that, so I want to show the next upcoming event. (24/05/2020)
What I currently have:
Json:
{
"doc": [
{
"data": {
"events": {
"18807612": {
"_dt": {
"_doc": "time",
"time": "18:45",
"date": "14/05/20",
"tz": "UTC",
"tzoffset": 0,
"uts": 1566067500
},
"week": 33,
"teams": {
"home": {
"name": "name 1",
"mediumname": "name1",
"uid": 3014
},
"away": {
"name": "name 2",
"mediumname": "name 2",
"uid": 3020
}
}
},
"18807618": {
"_dt": {
"_doc": "time",
"time": "18:45",
"date": "24/05/20",
"tz": "UTC",
"tzoffset": 0,
"uts": 1566067500
},
"week": 33,
"teams": {
"home": {
"name": "name 1",
"mediumname": "name1",
"uid": 3014
},
"away": {
"name": "name 2",
"mediumname": "name2",
"uid": 3020
}
}
}
}
}
}
]
}
Store:
async loadPosts({ commit }) {
// Define urls pages
const urlEvents = 'http://api.example.com/302020';
// Set pages
const [
responseEvents
] = await Promise.all([
// Responses pages
this.$axios.get(urlEvents)
]);
// variables pages
this.events = responseEvents.data.doc[0].data.events
// mutations pages
commit('SET_EVENTS', this.events)
}
},
mutations: {
SET_EVENTS (state, events) {
state.events = events;
}
}
And to show the data I use this:
import {mapState} from 'vuex';
export default {
name: 'NextMatch',
mounted() {
this.$store.dispatch('loadPosts')
},
computed: {
...mapState([
'events'
])
}
}
<h1>{{events}}</h1>
But this shows all data, and what I try to get is the first upcoming event for the object with the "uid": 3014.
So I want to show the date, time and names of the home and away team.
How can I get the correct data by filtering the data?
Something like this or similar to this should work:
In your Vue component's <template>:
`<h1>{{selectedEvent._dt.date}}</h1>`
In your Vue component's <script>:
props: {
eventID: {
type: Number,
default: 3014
},
},
computed: {
...mapState([
'events'
]),
eventsArr(){
if (!this.events) return {} //make sure Object.entries gets object.
return Object.entries(this.events)
},
selectedEvent(){
const selectedArr = this.eventsArr.find(([eID, e]) => e.teams.home.uid === this.eventID)
return selectedArr[1]
}
}

React native, redux and reselect - selector returns incorrect data

I have the following code:
select.js:
export const getNavigationRoutes = state => state.navigation.routes
export const getNavigationIndex = state => state.navigation.index
export const getNavigationTab = createSelector(
[getNavigationRoutes, getNavigationIndex],
(routes, index) => (routes[index])
)
export const getBackNavSupported = createSelector(
getNavigationTab, nevTab => nevTab.index !== 0
)
viewController.js:
import {connect} from 'react-redux'
import AppView from './AppView'
import { getBackNavSupported } from '../selectors
export default connect(
state => ({
backNavSupported: getBackNavSupported(state),
}))
)(AppView)
My state changes from
{
"index": 1,
"key": "root",
"routes": [
{
"key": "HomeTab",
"title": "Home",
"index": 0,
"routes": [ /* .... */ ]
},
{
"key": "FamilyTab",
"title": "Family",
"index": 0,
"iconName": "people",
"routes": [ /* .... */ ]
},
]
}
to
{
"index": 1,
"key": "root",
"routes": [
{
"key": "HomeTab",
"title": "Home",
"index": 0,
"routes": [ /* ... */ ]
},
{
"key": "FamilyTab",
"title": "Family",
"index": 1,
"routes": [ /* ... */ ]
}
]
}
I use backNavSupported in AppView, but when I check the value of backNavSupported after the state changes, I get false, which makes now sense to me...
What am I missing?
UPDATE
This how I use it in the component (maybe scope issues?):
componentDidMount() {
const { backNavSupported} = this.props
BackAndroid.addEventListener('hardwareBackPress', () => {
if (backNavSupported ) {
back()
return true
}
return false
})
}