FactoryGirl embed create_list into another create_list - factory-bot

I have the following code in my spec folder
let(:team_lead) { create(:user) }
let(:developers) { FactoryGirl.create_list(:user, 3) }
let(:project) { create(:project, team_lead: team_lead, users: [developers]) }
but it keep giving me this error
*** ActiveRecord::AssociationTypeMismatch Exception: User(#70271414797520) expected, got
[#<User id: 420, name: "Litzy Champlin", email: "dahlia#feil.net", created_at: "2018-05-25 02:59:17", updated_at: "2018-05-25 02:59:17", provider: nil, uid: nil, token: nil, token_expires_at: nil>,
#<User id: 421, name: "Missouri Hilll DDS", email: "elizabeth#sauerhaag.com", created_at: "2018-05-25 02:59:17", updated_at: "2018-05-25 02:59:17", provider: nil, uid: nil, token: nil, token_expires_at: nil>,
#<User id: 422, name: "Joel Williamson Sr.", email: "maurine#gutkowski.net", created_at: "2018-05-25 02:59:17", updated_at: "2018-05-25 02:59:17", provider: nil, uid: nil, token: nil, token_expires_at: nil>]
which is an instance of Array(#70271403139340)
I have this factorygirl in spec/factory/project.rb
FactoryGirl.define do
factory :project do
name { Faker::Name.name }
team_lead nil
factory :project_with_team_lead do
team_lead
end
end
end
The relations between projects and users model is has_and_belongs_to_many. I do not want remove the developers as I want to use it for more test cases. So how do I do this?

Related

How to get a field of an object in document?

I am not sure how to phrase this question properly but basically I have an "Order" Schema and each order model contains an array of product objects created using "Product" Schema
When I create an order, my req.body is this
body: {
orderItems: [ [Object] ],
shippingAddress: {
fullName: '123',
address: '1231',
city: '123',
postalCode: '123',
country: '123'
},
shippingPrice: 0,
paymentMethod: 'Stripe',
itemsPrice: 338,
totalPrice: 338
},
If I log req.body.orderItems, I can see each product object printed
{
_id: new ObjectId("62d51a3895cad3ca283302f3"),
name: 'Christmas Cake',
slug: 'christmas-cake',
image: '/images/cake.jpg',
shop: 'Custom Cakes',
category: 'food',
description: 'Custom baked christmas cake, pre-order needed.',
price: 70,
stock: 1,
rating: 3,
numReviews: 2,
__v: 2,
createdAt: 2022-07-18T08:30:48.931Z,
updatedAt: 2022-07-20T03:03:00.592Z,
}
{
_id: new ObjectId("62d7a8c126dcacfc13055e3d"),
name: 'cake',
slug: 'cake',
image: '/images/cake.jpg',
shop: 'Custom Cakes',
category: 'food',
description: 'cake',
price: 15,
stock: 2,
rating: 0,
numReviews: 0,
user: { _id: new ObjectId("62d51d57c08cd7e6675e8d45")},
reviews: [],
createdAt: 2022-07-20T07:03:29.372Z,
updatedAt: 2022-07-20T07:03:59.315Z,
__v: 0
}
But I am unable to obtain the 'shop' field. req.body.orderItems.shop returns undefined

$group and $lookup is not giving proper data

I am having code like this
const aggregate = [];
const lookup = {
$lookup: {
from: "balances",
localField: "accountNumber",
foreignField: "account_id",
as: "bankbalance",
},
};
const unwind = {
$unwind: "$bankbalance",
};
const match = {
$match: {
"bankbalance.date": {
$gte: startDate,
$lte: endDate,
},
userId: mongoose.Types.ObjectId(userId),
isActive: 1,
type: "accountType"
},
};
const group = {
$group: {
_id: '$_id',
accountNumber:{"$first":"$accountNumber"},
balances: {
$addToSet: { date: "$$ROOT.date", amount: "$$ROOT.amount" },
},
},
};
aggregate.push(lookup);
aggregate.push(unwind);
aggregate.push(group);
aggregate.push(match);
let data = await BankAccounts.aggregate(aggregate);
this code is giving me empty [] data, if I do not use $group then its giving data like this
{
_id: 611bc2c4f9649b2c6fe4007f,
bankId: 'string',
mask: '0000',
name: 'Plaid Checking',
userId: 611bc2794d9f391bf2cd7877,
accountNumber: 'xxxxxxxxxxxxxxxxxxx',
bankTokenId: xxxxxxxxxxxxxxxxxxxxxxxxxxx,
createdAt: 2021-08-17T14:08:04.058Z,
isConnected: true,
subtype: 'checking',
type: 'depository',
updatedAt: 2021-08-25T11:36:37.824Z,
isActive: 1,
bankbalance: {
_id: 61262b9bf9649b2c6fe7d67c,
ISODate: '2021-05-19T00:00:00.000Z',
account_id: 'xxxxxxxxxxxxxxxxxxxxxxxx',
userId: 611bc2794d9f391bf2cd7877,
ISOCountryCode: null,
accountId: xxxxxxxxxxxxxxxxxxxx,
amount: -1047.62,
bankTokenId: xxxxxxxxxxxxxxxxxxxx,
createdAt: 2021-08-25T11:37:26.960Z,
current: null,
date: '2021-05-19',
institutionId: xxxxxxxxxxxxxxxxxxxxxx,
isActive: 1,
unofficialCountryCode: null,
updatedAt: 2021-08-25T11:37:26.960Z
}
},
{
_id: 611bc2c4f9649b2c6fe4007f,
bankId: 'string',
mask: '0000',
name: 'Plaid Checking',
userId: 611bc2794d9f391bf2cd7877,
accountNumber: 'xxxxxxxxxxxxxxxxxxx',
bankTokenId: xxxxxxxxxxxxxxxxxxxxxxxxxxx,
createdAt: 2021-08-17T14:08:04.058Z,
isConnected: true,
subtype: 'checking',
type: 'depository',
updatedAt: 2021-08-25T11:36:37.824Z,
isActive: 1,
bankbalance: {
_id: 61262b99f9649b2c6fe7d671,
ISODate: '2021-05-24T00:00:00.000Z',
account_id: 'xxxxxxxxxxxxxxxxxxxxxxxx',
userId: 611bc2794d9f391bf2cd7877,
ISOCountryCode: null,
accountId: xxxxxxxxxxxxxxxxxxxx,
amount: -1137.02,
bankTokenId: xxxxxxxxxxxxxxxxxxxx,
createdAt: 2021-08-25T11:37:26.960Z,
current: null,
date: '2021-05-24',
institutionId: xxxxxxxxxxxxxxxxxxxxxx,
isActive: 1,
unofficialCountryCode: null,
updatedAt: 2021-08-25T11:37:26.960Z
}
}
this is giving all data record again and again, here reference between 2 collection is accountNumber and account_id. I want to group all records in 1 like
{
_id: 611bc2c4f9649b2c6fe4007f,
bankId: 'string',
mask: '0000',
name: 'Plaid Checking',
userId: 611bc2794d9f391bf2cd7877,
accountNumber: 'xxxxxxxxxxxxxxxxxxx',
bankTokenId: xxxxxxxxxxxxxxxxxxxxxxxxxxx,
createdAt: 2021-08-17T14:08:04.058Z,
isConnected: true,
subtype: 'checking',
type: 'depository',
updatedAt: 2021-08-25T11:36:37.824Z,
isActive: 1,
bankbalance: [{
_id: 61262b99f9649b2c6fe7d671,
ISODate: '2021-05-24T00:00:00.000Z',
account_id: 'xxxxxxxxxxxxxxxxxxxxxxxx',
userId: 611bc2794d9f391bf2cd7877,
ISOCountryCode: null,
accountId: xxxxxxxxxxxxxxxxxxxx,
amount: -1137.02,
bankTokenId: xxxxxxxxxxxxxxxxxxxx,
createdAt: 2021-08-25T11:37:26.960Z,
current: null,
date: '2021-05-24',
institutionId: xxxxxxxxxxxxxxxxxxxxxx,
isActive: 1,
unofficialCountryCode: null,
updatedAt: 2021-08-25T11:37:26.960Z
},
{
_id: 61262b9bf9649b2c6fe7d67c,
ISODate: '2021-05-19T00:00:00.000Z',
account_id: 'xxxxxxxxxxxxxxxxxxxxxxxx',
userId: 611bc2794d9f391bf2cd7877,
ISOCountryCode: null,
accountId: xxxxxxxxxxxxxxxxxxxx,
amount: -1047.62,
bankTokenId: xxxxxxxxxxxxxxxxxxxx,
createdAt: 2021-08-25T11:37:26.960Z,
current: null,
date: '2021-05-19',
institutionId: xxxxxxxxxxxxxxxxxxxxxx,
isActive: 1,
unofficialCountryCode: null,
updatedAt: 2021-08-25T11:37:26.960Z
}
]
}
also sort bankbalance by date. Any help! Thanks in advance!!
The stages are in the order
aggregate.push(lookup);
aggregate.push(unwind);
aggregate.push(group);
aggregate.push(match);
When the group stage executes, each document will have only the fields noted in that stage. i.e.
{
_id: 611bc2c4f9649b2c6fe4007f,
accountNumber: 'xxxxxxxxxxxxxxxxxxx',
balances: [ {date: ......, amount: .....} ]
}
When the match stage executes, the fields "bankbalance.date", userId, isActive, and type don't exist, so no documents satisfy the match.

mongodb pull function why not working in my situation?

i make simple board app. but i face scrab problem.
i want to pull data in scrabContent when people unscrab. but it doesnt' work. help me plz..
My Schema looks like this. scrabContent means contents that i scrab. So, when i scrab some contents, they are stored in scrabContent.
const userSchema = new mongoose.Schema({
email: {
type: String,
unique: true,
required: true,
},
password: {
type: String,
required: true,
},
name: {
type: String,
required:true,
unique: true,
},
follower : [String],
following : [String],
boardBookmark: [],
scrabContent: [],
songs: [],
songsView: {
type: Number,
default :0,
},
profileImage: {
type: String,
}
});
this is schema data example.
{
follower: [],
following: [],
boardBookmark: [
{
name: 'asd',
introduction: 'dsadad',
boardId: '603a4e485d99d993e0bfdfee'
}
],
scrabContent: [
{
commentsNum: 3,
likes: [],
image: [Array],
isDeleted: false,
_id: 603b67e1904622ca9ee2cddb,
title: 'ㄴㅁㅇㄹㅁㄴㄹㅁ',
content: 'ㅁㅇㄴㄹㅁㄹㅁㄴㄹㅁㄴㄹ',
postUser: 'umpa',
postUserId: 603751786587acfbf1052d34,
boardId: 603a4e485d99d993e0bfdfee,
time: '2021/02/28 18:52:32',
__v: 0
},
{
commentsNum: 5,
likes: [Array],
image: [Array],
isDeleted: false,
_id: 603b09f509dcb8b594c1f015,
title: '테스트',
content: 'ㅋㅋ',
postUser: 'umpa',
postUserId: 603751786587acfbf1052d34,
boardId: 603a4e485d99d993e0bfdfee,
time: '2021/02/28 12:11:47',
__v: 0
}
],
songs: [
{
id: '1469319400',
type: 'songs',
href: '/v1/catalog/kr/songs/1469319400',
attributes: [Object],
name: 'LOVE AGAIN'
},
{
id: '1265893529',
type: 'songs',
href: '/v1/catalog/kr/songs/1265893529',
attributes: [Object],
name: 'Get You (feat. Kali Uchis)'
},
{
id: '1265893532',
type: 'songs',
href: '/v1/catalog/kr/songs/1265893532',
attributes: [Object],
name: 'Best Part (feat. H.E.R.)'
},
{
id: '1356070221',
type: 'songs',
href: '/v1/catalog/kr/songs/1356070221',
attributes: [Object],
name: 'Daniel'
},
{
id: '1438474485',
type: 'songs',
href: '/v1/catalog/kr/songs/1438474485',
attributes: [Object],
name: 'Falling'
}
],
songsView: 0,
_id: 603a84d9760444a652d2cc72,
email: 'test',
password: '$2b$10$w8b85O6KQwGIZ0D1x0TGle.qofoEC43OKI5cMSf7tfqld12fSUWlu',
name: 'test',
__v: 0
}
and this is server code to pull. req.user._id means User Schema's _id(in this case: 603a84d9760444a652d2cc72). and req.params.id means Content _id(in this case: 603b67e1904622ca9ee2cddb) in ScrabContent.
router.delete('/deleteScrabContent/:id', requireAuth, async (req, res) => {
try {
await User.findOneAndUpdate({_id: req.user._id}, {$pull: {scrabContent: {_id: req.params.id}}}, {new: true});
} catch (err) {
return res.status(422).send(err.message);
}
});
i don't know why scrabContent doesn't work.. help me T^T

How do I upload info associated to different Model Types using AWS & GraphQL?

I have an app that I have been working on that allows users to upload a post and other users can send messages after seeing their post. I am using AWS Amplify as a backend and I am trying to store user messages in a DynamoDB table. I am able to successfully store user info in a DynamoDB table after they create an account and successfully upload a post. My problem starts when I try to message another user about their post.
I get this error after pressing send Failed to create graphql GraphQLResponseError<ChatMessage>: GraphQL service returned a successful response containing errors: [Amplify.GraphQLError(message: "The variables input contains a field name \'chatMessageAuthorId\' that is not defined for input object type \'CreateChatMessageInput\' ", locations: nil, path: nil, extensions: nil)] Recovery suggestion: The list of `GraphQLError` contains service-specific messages
My GraphQL Schema is the following:
type User
#model
#auth(rules: [{ allow: owner, operations: [create, delete, update]}]) {
id: ID!
userSub: String!
fullName: String!
conversations: [ConvoLink] #connection(name: "UserLinks")
messages: [ChatMessage] #connection(name: "UserMessages", keyField: "authorId")
createdAt: String
updatedAt: String
}
type Conversation
#model
#auth(rules: [{ allow: owner, ownerField: "members" }]) {
id: ID!
messages: [ChatMessage] #connection(name: "ConvoMsgs", sortField: "createdAt")
associated: [ConvoLink] #connection(name: "AssociatedLinks")
name: String!
members: [String!]!
createdAt: String
updatedAt: String
}
type ChatMessage
#model
#auth(rules: [{ allow: owner, ownerField: "authorId" }]) {
id: ID!
author: User #connection(name: "UserMessages", keyField: "authorId")
authorId: String
content: String!
conversation: Conversation! #connection(name: "ConvoMsgs")
messageConversationId: ID!
createdAt: String
updatedAt: String
}
type ConvoLink
#model(
mutations: { create: "createConvoLink", update: "updateConvoLink" }
queries: null
subscriptions: null
) {
id: ID!
user: User! #connection(name: "UserLinks")
convoLinkUserId: ID
conversation: Conversation! #connection(name: "AssociatedLinks")
convoLinkConversationId: ID!
createdAt: String
updatedAt: String
}
type Post #model
#auth(rules: [{ allow: owner, operations: [create, delete, update] }]) {
id: ID!
userSub: String!
filename: String!
description: String!
dateUploaded: String!
}
And this is my Swift code to send a message to another user.
#objc func sendMessage(){
currentUserSub = AWSMobileClient.default().userSub!
guard let message = messageBox.text else{return}
let formatter = DateFormatter()
formatter.dateFormat = "h:mm a"
let hourString = formatter.string(from: Date())
let user = User(userSub: currentUserSub, fullName: userFullName)
let conversation = Conversation(messages: List<ChatMessage>.init(), associated: List<ConvoLink>.init(), name: "Chat between \(currentUserSub) & \(otherUserSub)", members: [currentUserSub,otherUserSub], createdAt: hourString, updatedAt: hourString)
let chatMessage = ChatMessage(author: user, authorId: currentUserSub, content: message, conversation: conversation, messageConversationId: "\(currentUserSub) & \(otherUserSub)", createdAt: hourString, updatedAt: hourString)
_ = Amplify.API.mutate(request: .create(chatMessage)) { event in
switch event {
case .success(let result):
switch result {
case .success(let convo):
DispatchQueue.main.async {
print("Successfully created the convo: \(convo)")
self.messageButton.setTitle("Message Sent", for: .normal)
self.messageButton.isEnabled = false
}
case .failure(let graphQLError):
DispatchQueue.main.async {
print("Failed to create graphql \(graphQLError)")
self.messageButton.setTitle("An error has occured, try again.", for: .normal)
// self.checkIfOffline()
}
}
case .failure(let apiError):
print("Failed to create a message", apiError)
// self.checkIfOffline()
}
}
hideKeyboard()
print(message)
}
Can anyone tell me what I am doing wrong? I am fairly new to GraphQL and AWS.

Syntax error Unexpected token ILLEGAL Mongo Console

I'm trying to remove a document from an array threads that is a field in the collection's head document.
In Mongodb console I write following query:
db.inboxes.update({}, { $pull: {threads: {"_id":ObjectId(”5550b41ce7c33013c8000006”)}}})
But I keep getting:
Unexpected token ILLEGAL
It's driving me crazy. The Collection's schema is as following:
var inboxSchema = mongoose.Schema({
user: {
type: mongoose.Schema.ObjectId,
ref: 'userSchema',
required: true
},
threads: [{
name: String,
guid: String,
with: {
_id: {
type: mongoose.Schema.ObjectId,
ref: 'userSchema'
},
name: {
username: String,
firstname: String,
lastname: String
},
email: {
type: String,
match: /\S+#\S+\.\S+/
}
},
messages: [{
heading: String,
sent: {
type: Date,
default: Date.now
},
from: {
type: mongoose.Schema.ObjectId,
ref: 'userSchema'
},
to: {
type: mongoose.Schema.ObjectId,
ref: 'userSchema'
},
body: String
}],
updated: {
type: Date,
default: Date.now
},
unreadMessage: Boolean
}]
});
Take a look at your query
db.inboxes.update({}, { $pull: {threads: {"_id":ObjectId(”5550b41ce7c33013c8000006”)}}})
in ObjectId argument you have wrong quote marks ” instead of ". Replace them and you will get rid of the error :)