Below is my code to update values in my MongoDB using mongoose. It updates only the first item in the array but not the second one.
I want this code to update both the items.
router.post('/updateattendance', (req, res) => {
let attendaceColl = [
{roll_number: 9915,date: '2019-05-21',was_present: true},
{roll_number: 9904,date: '2019-05-21',was_present: true}
];
async.eachSeries(attendaceColl, (stdnt, done) => {
UserSubjectDetails.findOneAndUpdate(
{
roll_number: stdnt.roll_number
},
{
$push: {
'subject_details.attendance.doc' : [{
date: stdnt.date,
was_present: stdnt.was_present
}]
}
}, function(err, rsesult) {
console.log('did')
}, done);
}, function(err, res){
console.log(res)
});
});
Related
Hello this is my first time. I have problem with like that I have 3000 items and I use framework like vue, element-ui and meteor. I pull all the items through a remote el-select that selects to add more remote select array object.I don't know why it slow performance and crush.
This is my picture
// Find item opts method
_getItemOpts(query, type) {
type = type || 'remote'
let exp = new RegExp(query)
let selector = {}
if (exp) {
selector = {
itemType: { $ne: 'Bundle' },
// , 'Sale'
activityType: { $in: ['Purchase'] },
status: 'Active',
$or: [
{ name: { $regex: exp, $options: 'i' } },
{ refNo: { $regex: exp, $options: 'i' } },
{ barcode: { $regex: exp, $options: 'i' } },
],
}
}
// Find item
findItems
.callPromise({ selector: selector })
.then(result => {
// console.log(result)
if (type == 'remote') {
this.itemOpts = result
}
this.loading = false
})
.catch(err => {
this.loading = false
Notify.error({ message: err })
})
},
Please help me.
Well no magick is here. U tryin to add to DOM 3000 of elements, so no wonder its crashes. Try to narrow results, for example show them only when user enters 3 letters
This is the DynamoDB table structure I'm working on:
{
"userId": "99999999-9999-9999-9999-999999999999",
"userProfile": {
"email": "myemail#gmail.com",
"firstName": "1234124",
"lastName": "123423",
},
"masterCards": [
{
"cardId": 101000000000001,
"cardImage": "logo.png",
"cardName": "VipCard1",
"cardWallet": "0xFDB17d12057b6Fe8c8c425D2DB88d8475674567"
},
{
"cardId": 102000000000002,
"cardImage": "logo.png",
"cardName": "VipCard2",
"cardWallet": "0xFDB17d12057b6Fe8c8c425D2DB88d8183454345"
},
{
"cardId": 103000000000003,
"cardImage": "logo.png",
"cardName": "VipCard3",
"cardWallet": "0xFDB17d12057b6Fe8c8c425D2DB88d8184345345"
}
],
}
I'm trying to increase the cardId field by one for the first list item with this Lambda function:
const dynamoDB = new AWS.DynamoDB({region: 'eu-central-1', apiVersion:'2012-08-10'});
const counterId="99999999-9999-9999-9999-999999999999"
const params = {
TableName:"FidelityCardsUsers",
Key: {"userId":{"S":counterId}},
UpdateExpression:"ADD #masterCards[0].#cardId :increment",
ExpressionAttributeNames:{
"#masterCards": "masterCards",
"#cardId": "cardId"
},
ExpressionAttributeValues:{":increment": {"N": "1"}}
}
dynamoDB.updateItem(params, function(err, data) {
if (err) {
console.log('error getting counter from DynamDB: ',err)
callback(err);
} else {
callback(null,data)
}
})
In return I get only a new top-level attribute named "mastercards[0].cardId[0]" with a value number set to 1.
I have tried to increment In an array and its work fine with AWS.DynamoDB.DocumentClient()
Example :
var AWS = require("aws-sdk");
var docClient = new AWS.DynamoDB.DocumentClient();
let params = {
TableName:'tableName',
Key: {
'venueId': 'VENUE_002'
},
UpdateExpression: "ADD #walk.#coordinates[0] :increment",
ExpressionAttributeNames: {
'#walk': 'walk',
'#coordinates': 'coordinates'
},
ExpressionAttributeValues: {
':increment': 1 // This is from the client
},
ReturnValues: 'UPDATED_NEW'
};
docClient.update(params, function (err, data) {
if (err) {
console.log('failure:updateShuttleDirection:failed');
console.log(err);
} else {
console.log('success:updateShuttleDirection:complete');
console.log(data);
}
});
Sample Data:
"walk": {
"coordinates": [
10,
20
],
"type": "Point"
},
I have tried to increment 10 to 11 and its work fine
Reading the doc here, it seems that:
the ADD action can only be used on top-level attributes, not nested
attributes.
Im new in Vuejs. I started a project with Vue, Firebase and using Chart Js inside of it. Here is the details of problem.
If I give any value of sales_today in data() it shows properly on mounted where I use it by this.sales_today also works perfectly in template {{sales_today}}.
But into the Created I'm trying to change this.sales_today value by an output of firebase query. then the output shows perfectly into template {{sales_today}} but not working inside the mounted here
**data: [this.sales_today,30,60,10]**
Template
<template>
{{sales_today}}
</template>
Data
data(){
return{
sales_today:''
}
},
Mounted
mounted() {
data: {
datasets: [{
data: [this.sales_today,30,60,10],
}]
}
}
Created
created(){
let ref = db.collection('sales').where("sales_date", "==", moment().format('DD-MM-YYYY'))
.get()
.then(snapshot => {
var total = 0;
snapshot.forEach(doc => {
total += Number(doc.data().price)
})
this.sales_today = total
})
}
Here is the complete code
https://github.com/Shakilzaman87/pukucrm/blob/master/src/components/dashboard/Dashboard.vue
This should be on mounted(). I don't have the editor on comments and i will answer here.
let ref = db.collection('sales').where("sales_date", "==", moment().format('DD-MM-YYYY'))
.get()
.then(snapshot => {
var total = 0;
snapshot.forEach(doc => {
total += Number(doc.data().price)
})
this.sales_today = total;
var chart = this.$refs.chart;
var ctx = chart.getContext("2d");
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels:this.labels,
datasets: [{
label: 'Sales of June',
data: [this.sales_today,30,60,10],
backgroundColor: [
'#ffffff'
],
borderColor: [
'#1976d2'
],
borderWidth: 3
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
},
});
})
P.S. check the console for errors
In GraphiQL at http://localhost:8080/graphiql, I'm using this query:
{
instant_message(fromID: "1"){
fromID
toID
msgText
}
}
I'm getting this response:
{
"data": {
"instant_message": {
"fromID": null,
"toID": null,
"msgText": null
}
},
"errors": [
{
"message": "Resolve function for \"instant_message.fromID\" returned undefined",
"locations": [
{
"line": 3,
"column": 5
}
]
},
{
"message": "Resolve function for \"instant_message.toID\" returned undefined",
"locations": [
{
"line": 4,
"column": 5
}
]
},
{
"message": "Resolve function for \"instant_message.msgText\" returned undefined",
"locations": [
{
"line": 5,
"column": 5
}
]
}
]
}
I tried to set up my system according to the examples found here:
https://medium.com/apollo-stack/tutorial-building-a-graphql-server-cddaa023c035#.s7vjgjkb7
Looking at that article, it doesn't seem to be necessary to set up individual resolvers for string fields, but I must be missing something.
What is the correct way to update my resolvers so as to return results from string fields? Example code would be greatly appreciated!
Thanks very much in advance to all for any thoughts or info.
CONNECTORS
import Sequelize from 'sequelize';
//SQL CONNECTORS
const db = new Sequelize(Meteor.settings.postgres.current_dev_system.dbname, Meteor.settings.postgres.current_dev_system.dbuser, Meteor.settings.postgres.current_dev_system.dbpsd, {
host: 'localhost',
dialect: 'postgres',
});
db
.authenticate()
.then(function(err) {
console.log('Connection to Sequelize has been established successfully.');
})
.catch(function (err) {
console.log('Unable to connect to the Sequelize database:', err);
});
const IMModel = db.define('IM', {
id: {type: Sequelize.INTEGER, primaryKey: true, autoIncrement: true},
fromID: {type: Sequelize.STRING},
toID: {type: Sequelize.STRING},
msgText: {type: Sequelize.STRING}
});
IMModel.sync({force: true}).then(function () {
// Table created
return IMModel.create({
fromID: '1',
toID: '2',
msgText: 'msg set up via IMModel.create'
});
});
const IM = db.models.IM;
export {db, IM };
SCHEMA
const typeDefinitions = [`
type instant_message {
id: Int
fromID: String
toID: String
msgText: String
}
type Query {
instant_message(fromID: String, toID: String, msgText: String): instant_message
}
type RootMutation {
createInstant_message(
fromID: String!
toID: String!
msgText: String!
): instant_message
}
schema {
query: Query,
mutation: RootMutation
}
`];
export default typeDefinitions;
RESOLVERS
import * as connectors from './db-connectors';
import { Kind } from 'graphql/language';
const b = 100;
const resolvers = {
Query: {
instant_message(_, args) {
const a = 100;
return connectors.IM.find({ where: args });
}
},
RootMutation: {
createInstant_message: (__, args) => { return connectors.IM.create(args); },
},
};
export default resolvers;
When you define your GraphQLObjectTypes you need to provide a resolver for each of their fields.
You defined your instant_message with multiple fields but did not provide resolvers for each of these fields.
More over you defined the types of those field with regular typescript fields while you need to define it with GraphQL types (GraphQLInt, GraphQLString, GrapQLFloat etc..)
So defining your type should look something like this:
let instant_message = new GraphQLObjectType({
id: {
type: GraphQLInt,
resolve: (instantMsg)=> {return instantMsg.id}
}
fromID: {
type: GraphQLString,
resolve: (instantMsg)=> {return instantMsg.fromID}
}
toID: {
type: GraphQLString,
resolve: (instantMsg)=> {return instantMsg.toID}
}
msgText: {
type: GraphQLString,
resolve: (instantMsg)=> {return instantMsg.msgText}
}
})
In addition, you will need to define your Query as follows:
let Query = new GraphQLObjectType({
name: "query",
description: "...",
fields: () => ({
instant_messages: {
type: new GraphQLList(instant_message),
args: {
id: {type: GraphQLInt}
},
resolve: (root, args) => {
connectors.IM.find({ where: args })
}
}
})
})
The issue is that the query does not expect an array,
Please fix it:
type Query {
instant_message(fromID: String, toID: String, msgText: String): [instant_message]
}
Then you should make sure the resolver returns Array of objects, if it doesnt work then the resolver is not returning an Array.
Problem:
I have a number of groups that each have members that belong to different groups. Each member has a title (role) in each group.
I’m trying to list all the groups and display each member in the group and their title.
I’m using reywood:publish-composite, and everything is working except I can’t get the title of each member to display.
I think the problem is in the Template.groupMembers.helpers file
title: function() {
console.log(this.roleId); // this shows up in the console for each member
return Titles.findOne({titleId: this.roleId}); // but this doesn’t work
},
Collections:
groups {
"_id" : "xFSzAHBEps2dSKcWM",
"name" : "Generic Group",
"logo" : "generic-logo-hi.png"
}
members {
"_id" : "vyDtiaKKukZYQdFvs",
"groupId" : "xFSzAHBEps2dSKcWM",
"memberId" : "hRx8GBTyB5X8iQQ52",
"roleId" : "1"
}
Meteor.users {
"_id" : "hRx8GBTyB5X8iQQ52",
"profile" : {
"name" : "Bob Lorros"
},
}
titles {
"_id" : "bYsKpsyYtyKR8NYpm",
"titleId" : 1,
"title" : "Staff (non-voting)"
}
server/publications/publications.js
Meteor.publishComposite('groupMembers', {
find: function() {
return Groups.find({}, {
sort: {name: 1}
});
},
children: [
{
find: function() {
return Titles.find();
},
find: function(group) {
return Members.find({groupId: group._id});
},
children: [
{
find: function(member) {
return Meteor.users.find({_id: member.memberId});
}
},
]
},
]
});
client/templates/test/test.js
Template.groupMembers.helpers({
groupMembers: function() {
return Groups.find({}, {
sort: {name: 1}
});
},
members: function() {
return Members.find({groupId: this._id});
},
title: function() {
console.log(this.roleId); // this shows up in the console for each member
return Titles.findOne({titleId: this.roleId}); // but this doesn’t work
},
memberName: function() {
return Meteor.users.findOne(this.memberId);
},
});
client/templates/test/test.html
<template name="groupMembers">
<h4>Group - Members</h4>
{{#each groupMembers}}
<b>{{name}}</b><br>
{{#each members}}
{{memberName.profile.name}}
- title = {{title.title}}
<br>
{{/each}}
<br>
{{/each}}
</template>
Output :
This is the ouput
Looking at this from a completely different perspective, I actually think you could use alanning:roles to accomplish exactly what you're looking for. You can use the role as the 'title' in this case and the 'group' to replace your groups. Here's the documentation:
https://github.com/alanning/meteor-roles
Not sure but I think your second find may be overriding your first. Instead of:
find: function() {
return Titles.find();
},
find: function(group) {
return Members.find({groupId: group._id});
},
Try returning an array of cursors.
find: function() {
return [
Titles.find(),
Members.find({groupId: group._id})
];
},
I don't understand however why Titles is a child of GroupMembers when the query for titles is all titles. Did you mean to have a query there?
I think your publishComposite is causing the problem, each object in the children array should have only one find and zero or more children. Also the second parameter in your publication must be a function and not a JSON object. Try this,
Meteor.publishComposite('groupMembers', function () {
return {
find: function() {
return Groups.find({}, {
sort: {name: 1}
});
},
children: [{
find: function() {
return Titles.find();
}
},
{
find: function(group) {
return Members.find({groupId: group._id});
},
children: [{
find: function(member) {
return Meteor.users.find({_id: member.memberId});
}
}]
}]
};
});
You can also improve performance by moving Titles.find to the root level
Meteor.publishComposite('groupMembers', function () {
return [{
find: function() {
return Titles.find();
}
}, {
find: function() {
return Groups.find({}, {
sort: {name: 1}
});
},
children: [{
find: function(group) {
return Members.find({groupId: group._id});
},
children: [{
find: function(member) {
return Meteor.users.find({_id: member.memberId});
}
}]
}]
}];
});