Not able to save a custom object array save to UserDefault in Swift 4 - cncontact

I have searched for around 2 days on Google and also on StackOverflow but no luck.
My custom object is almost a replica of the CNContact object.
struct Contact: Codable {
let fullName, phones, emails: String
let imageDataAvailable, expanded: Bool
let thumbnailImageData, imageData: Data
let contactType: Int
let identifier: String
let namePrifix, givenName, middleName, familyName, previousFamilyName, nameSuffix, nickName, organizationName, departmentName, jobTitle, phoneticGivenName, phoneticMiddleName, phoneticFamilyName, phoneticOrganizationName, note: String
let birthday, nonGregorianBirthday: DateComponents
let dates: [ContactDate]
let postalAddresses: [PostalAddress]
let urlAddresses: [UrlAddress]
let contactRelations: [ContactRelation]
let socialProfiles: [SocialProfile]
let instantMessageAddresses: [InstantMessageAddress]
let phoneNumbers: [PhoneNumber]
let emailAddresses: [Email]
}
struct PostalAddress: Codable {
let label, street, subLocality, city, subAdministativeArea, state, postalCode, country, isoCountryCode: String
}
struct UrlAddress: Codable {
let label, value: String
}
struct ContactRelation: Codable {
let label, name: String
}
struct SocialProfile: Codable {
let label, urlString, userName, userIdentifier, service: String
}
struct PhoneNumber: Codable {
let label, stringValue: String
}
struct Email: Codable {
let label, value: String
}
struct InstantMessageAddress: Codable {
let label, userName, service: String
}
struct ContactDate: Codable {
let label: String
let value: DateComponents
}
I try to save an array of the Contact object to UserDefault but all time it just gives me the same error.
Please help me with solving this issue.
Edit 1
I tried to convert the array to data using the below code but no luck I got another error
Code
do {
let contactJson = try JSONSerialization.data(withJSONObject: arrContact, options: .prettyPrinted)
CommonFunctions.setUserDefaultValue(key: WSKey.contacts.rawValue, value: contactJson)
} catch let parsingError {
print("Error", parsingError)
}
ERROR
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Invalid type in JSON write (_SwiftValue)'
My array with debugDescription command in log is as follow
"[Storedge.Contact(fullName: \"Kate Bell\", phones: \"(555) 564-8583\n(415) 555-3695\", emails: \"kate-bell#mac.com\", imageDataAvailable: false, expanded: false, thumbnailImageData: 0 bytes, imageData: 0 bytes, contactType: 0, identifier: \"177C371E-701D-42F8-A03B-C61CA31627F6\", namePrifix: \"\", givenName: \"Kate\", middleName: \"\", familyName: \"Bell\", previousFamilyName: \"\", nameSuffix: \"\", nickName: \"\", organizationName: \"Creative Consulting\", departmentName: \"\", jobTitle: \"Producer\", phoneticGivenName: \"\", phoneticMiddleName: \"\", phoneticFamilyName: \"\", phoneticOrganizationName: \"\", note: \"\", birthday: calendar: gregorian (fixed) year: 1978 month: 1 day: 20 isLeapMonth: false , nonGregorianBirthday: isLeapMonth: false , dates: [], postalAddresses: [Storedge.PostalAddress(label: \"$!!$\", street: \"165 Davis Street\", subLocality: \"\", city: \"Hillsborough\", subAdministativeArea: \"\", state: \"CA\", postalCode: \"94010\", country: \"\", isoCountryCode: \"us\")], urlAddresses: [Storedge.UrlAddress(label: \"$!!$\", value: \"www.icloud.com\")], contactRelations: [], socialProfiles: [], instantMessageAddresses: [], phoneNumbers: [Storedge.PhoneNumber(label: \"$!!$\", stringValue: \"(555) 564-8583\"), Storedge.PhoneNumber(label: \"$!!$\", stringValue: \"(415) 555-3695\")], emailAddresses: [Storedge.Email(label: \"$!!$\", value: \"kate-bell#mac.com\")]), Storedge.Contact(fullName: \"Daniel Higgins\", phones: \"555-478-7672\n(408) 555-5270\n(408) 555-3514\", emails: \"d-higgins#mac.com\", imageDataAvailable: false, expanded: false, thumbnailImageData: 0 bytes, imageData: 0 bytes, contactType: 0, identifier: \"AB211C5F-9EC9-429F-9466-B9382FF61035\", namePrifix: \"\", givenName: \"Daniel\", middleName: \"\", familyName: \"Higgins\", previousFamilyName: \"\", nameSuffix: \"Jr.\", nickName: \"\", organizationName: \"\", departmentName: \"\", jobTitle: \"\", phoneticGivenName: \"\", phoneticMiddleName: \"\", phoneticFamilyName: \"\", phoneticOrganizationName: \"\", note: \"Sister: Emily\", birthday: isLeapMonth: false , nonGregorianBirthday: isLeapMonth: false , dates: [], postalAddresses: [Storedge.PostalAddress(label: \"$!!$\", street: \"332 Laguna Street\", subLocality: \"\", city: \"Corte Madera\", subAdministativeArea: \"\", state: \"CA\", postalCode: \"94925\", country: \"USA\", isoCountryCode: \"us\")], urlAddresses: [], contactRelations: [], socialProfiles: [], instantMessageAddresses: [], phoneNumbers: [Storedge.PhoneNumber(label: \"$!!$\", stringValue: \"555-478-7672\"), Storedge.PhoneNumber(label: \"$!!$\", stringValue: \"(408) 555-5270\"), Storedge.PhoneNumber(label: \"$!!$\", stringValue: \"(408) 555-3514\")], emailAddresses: [Storedge.Email(label: \"$!!$\", value: \"d-higgins#mac.com\")]), Storedge.Contact(fullName: \"John Appleseed\", phones: \"888-555-5512\n888-555-1212\", emails: \"John-Appleseed#mac.com\", imageDataAvailable: false, expanded: false, thumbnailImageData: 0 bytes, imageData: 0 bytes, contactType: 0, identifier: \"410FE041-5C4E-48DA-B4DE-04C15EA3DBAC\", namePrifix: \"\", givenName: \"John\", middleName: \"\", familyName: \"Appleseed\", previousFamilyName: \"\", nameSuffix: \"\", nickName: \"\", organizationName: \"\", departmentName: \"\", jobTitle: \"\", phoneticGivenName: \"\", phoneticMiddleName: \"\", phoneticFamilyName: \"\", phoneticOrganizationName: \"\", note: \"College roommate\", birthday: calendar: gregorian (fixed) year: 1980 month: 6 day: 22 isLeapMonth: false , nonGregorianBirthday: isLeapMonth: false , dates: [], postalAddresses: [Storedge.PostalAddress(label: \"$!!$\", street: \"3494 Kuhl Avenue\", subLocality: \"\", city: \"Atlanta\", subAdministativeArea: \"\", state: \"GA\", postalCode: \"30303\", country: \"USA\", isoCountryCode: \"us\"), Storedge.PostalAddress(label: \"$!!$\", street: \"1234 Laurel Street\", subLocality: \"\", city: \"Atlanta\", subAdministativeArea: \"\", state: \"GA\", postalCode: \"30303\", country: \"USA\", isoCountryCode: \"us\")], urlAddresses: [], contactRelations: [], socialProfiles: [], instantMessageAddresses: [], phoneNumbers: [Storedge.PhoneNumber(label: \"$!!$\", stringValue: \"888-555-5512\"), Storedge.PhoneNumber(label: \"$!!$\", stringValue: \"888-555-1212\")], emailAddresses: [Storedge.Email(label: \"$!!$\", value: \"John-Appleseed#mac.com\")]), Storedge.Contact(fullName: \"Anna Haro\", phones: \"555-522-8243\", emails: \"anna-haro#mac.com\", imageDataAvailable: false, expanded: false, thumbnailImageData: 0 bytes, imageData: 0 bytes, contactType: 0, identifier: \"F57C8277-585D-4327-88A6-B5689FF69DFE\", namePrifix: \"\", givenName: \"Anna\", middleName: \"\", familyName: \"Haro\", previousFamilyName: \"\", nameSuffix: \"\", nickName: \"Annie\", organizationName: \"\", departmentName: \"\", jobTitle: \"\", phoneticGivenName: \"\", phoneticMiddleName: \"\", phoneticFamilyName: \"\", phoneticOrganizationName: \"\", note: \"\", birthday: calendar: gregorian (fixed) year: 1985 month: 8 day: 29 isLeapMonth: false , nonGregorianBirthday: isLeapMonth: false , dates: [Storedge.ContactDate(label: \"$!!$\", value: calendar: gregorian (fixed) year: 2002 month: 2 day: 15 isLeapMonth: false ), Storedge.ContactDate(label: \"$!!$\", value: calendar: gregorian (fixed) year: 2002 month: 2 day: 15 isLeapMonth: false )], postalAddresses: [Storedge.PostalAddress(label: \"$!!$\", street: \"1001 Leavenworth Street\", subLocality: \"\", city: \"Sausalito\", subAdministativeArea: \"\", state: \"CA\", postalCode: \"94965\", country: \"USA\", isoCountryCode: \"us\")], urlAddresses: [], contactRelations: [], socialProfiles: [], instantMessageAddresses: [], phoneNumbers: [Storedge.PhoneNumber(label: \"$!!$\", stringValue: \"555-522-8243\")], emailAddresses: [Storedge.Email(label: \"$!!$\", value: \"anna-haro#mac.com\")]), Storedge.Contact(fullName: \"Hank M. Zakroff\", phones: \"(555) 766-4823\n(707) 555-1854\", emails: \"hank-zakroff#mac.com\", imageDataAvailable: false, expanded: false, thumbnailImageData: 0 bytes, imageData: 0 bytes, contactType: 0, identifier: \"2E73EE73-C03F-4D5F-B1E8-44E85A70F170\", namePrifix: \"\", givenName: \"Hank\", middleName: \"M.\", familyName: \"Zakroff\", previousFamilyName: \"\", nameSuffix: \"\", nickName: \"\", organizationName: \"Financial Services Inc.\", departmentName: \"\", jobTitle: \"Portfolio Manager\", phoneticGivenName: \"\", phoneticMiddleName: \"\", phoneticFamilyName: \"\", phoneticOrganizationName: \"\", note: \"\", birthday: isLeapMonth: false , nonGregorianBirthday: isLeapMonth: false , dates: [], postalAddresses: [Storedge.PostalAddress(label: \"$!!$\", street: \"1741 Kearny Street\", subLocality: \"\", city: \"San Rafael\", subAdministativeArea: \"\", state: \"CA\", postalCode: \"94901\", country: \"\", isoCountryCode: \"us\")], urlAddresses: [], contactRelations: [], socialProfiles: [], instantMessageAddresses: [], phoneNumbers: [Storedge.PhoneNumber(label: \"$!!$\", stringValue: \"(555) 766-4823\"), Storedge.PhoneNumber(label: \"$!!$\", stringValue: \"(707) 555-1854\")], emailAddresses: [Storedge.Email(label: \"$!!$\", value: \"hank-zakroff#mac.com\")]), Storedge.Contact(fullName: \"David Taylor\", phones: \"555-610-6679\", emails: \"\", imageDataAvailable: false, expanded: false, thumbnailImageData: 0 bytes, imageData: 0 bytes, contactType: 0, identifier: \"E94CD15C-7964-4A9B-8AC4-10D7CFB791FD\", namePrifix: \"\", givenName: \"David\", middleName: \"\", familyName: \"Taylor\", previousFamilyName: \"\", nameSuffix: \"\", nickName: \"\", organizationName: \"\", departmentName: \"\", jobTitle: \"\", phoneticGivenName: \"\", phoneticMiddleName: \"\", phoneticFamilyName: \"\", phoneticOrganizationName: \"\", note: \"Plays on Cole\\'s Little League Baseball Team\n\", birthday: calendar: gregorian (fixed) year: 1998 month: 6 day: 15 isLeapMonth: false , nonGregorianBirthday: isLeapMonth: false , dates: [], postalAddresses: [Storedge.PostalAddress(label: \"$!!$\", street: \"1747 Steuart Street\", subLocality: \"\", city: \"Tiburon\", subAdministativeArea: \"\", state: \"CA\", postalCode: \"94920\", country: \"USA\", isoCountryCode: \"us\")], urlAddresses: [], contactRelations: [], socialProfiles: [], instantMessageAddresses: [], phoneNumbers: [Storedge.PhoneNumber(label: \"$!!$\", stringValue: \"555-610-6679\")], emailAddresses: []), Storedge.Contact(fullName: \"mavya.soni#jayatma.com \", phones: \"\", emails: \"mavya.soni#jayatma.com\", imageDataAvailable: false, expanded: false, thumbnailImageData: 0 bytes, imageData: 0 bytes, contactType: 0, identifier: \"F01A8F75-B1E0-4B72-A017-6FDE693BE4E4\", namePrifix: \"\", givenName: \"mavya.soni#jayatma.com\", middleName: \"\", familyName: \"\", previousFamilyName: \"\", nameSuffix: \"\", nickName: \"\", organizationName: \"\", departmentName: \"\", jobTitle: \"\", phoneticGivenName: \"\", phoneticMiddleName: \"\", phoneticFamilyName: \"\", phoneticOrganizationName: \"\", note: \"\", birthday: isLeapMonth: false , nonGregorianBirthday: isLeapMonth: false , dates: [], postalAddresses: [], urlAddresses: [], contactRelations: [], socialProfiles: [], instantMessageAddresses: [], phoneNumbers: [], emailAddresses: [Storedge.Email(label: \"$!!$\", value: \"mavya.soni#jayatma.com\")]), Storedge.Contact(fullName: \"Dimple Shah\", phones: \"\", emails: \"\", imageDataAvailable: false, expanded: false, thumbnailImageData: 0 bytes, imageData: 0 bytes, contactType: 0, identifier: \"4B0CE4C4-6569-4936-8C45-34A15725DF9D\", namePrifix: \"\", givenName: \"Dimple\", middleName: \"\", familyName: \"Shah\", previousFamilyName: \"\", nameSuffix: \"\", nickName: \"\", organizationName: \"\", departmentName: \"\", jobTitle: \"\", phoneticGivenName: \"\", phoneticMiddleName: \"\", phoneticFamilyName: \"\", phoneticOrganizationName: \"\", note: \"\", birthday: isLeapMonth: false , nonGregorianBirthday: isLeapMonth: false , dates: [], postalAddresses: [], urlAddresses: [], contactRelations: [], socialProfiles: [], instantMessageAddresses: [], phoneNumbers: [], emailAddresses: []), Storedge.Contact(fullName: \"yash.soni#jayatma.com \", phones: \"\", emails: \"yash.soni#jayatma.com\", imageDataAvailable: false, expanded: false, thumbnailImageData: 0 bytes, imageData: 0 bytes, contactType: 0, identifier: \"36C2E9A2-3955-49C7-BCED-02CDD1622E69\", namePrifix: \"\", givenName: \"yash.soni#jayatma.com\", middleName: \"\", familyName: \"\", previousFamilyName: \"\", nameSuffix: \"\", nickName: \"\", organizationName: \"\", departmentName: \"\", jobTitle: \"\", phoneticGivenName: \"\", phoneticMiddleName: \"\", phoneticFamilyName: \"\", phoneticOrganizationName: \"\", note: \"\", birthday: isLeapMonth: false , nonGregorianBirthday: isLeapMonth: false , dates: [], postalAddresses: [], urlAddresses: [], contactRelations: [], socialProfiles: [], instantMessageAddresses: [], phoneNumbers: [], emailAddresses: [Storedge.Email(label: \"$!!$\", value: \"yash.soni#jayatma.com\")]), Storedge.Contact(fullName: \"Bhavesh Panchal\", phones: \"\", emails: \"Bhavesh.panchal#jayatma.com\", imageDataAvailable: false, expanded: false, thumbnailImageData: 0 bytes, imageData: 0 bytes, contactType: 0, identifier: \"564EB186-036C-437D-952D-A09A85A21027\", namePrifix: \"\", givenName: \"Bhavesh\", middleName: \"\", familyName: \"Panchal\", previousFamilyName: \"\", nameSuffix: \"\", nickName: \"\", organizationName: \"\", departmentName: \"\", jobTitle: \"\", phoneticGivenName: \"\", phoneticMiddleName: \"\", phoneticFamilyName: \"\", phoneticOrganizationName: \"\", note: \"\", birthday: isLeapMonth: false , nonGregorianBirthday: isLeapMonth: false , dates: [], postalAddresses: [], urlAddresses: [], contactRelations: [], socialProfiles: [], instantMessageAddresses: [], phoneNumbers: [], emailAddresses: [Storedge.Email(label: \"$!!$\", value: \"Bhavesh.panchal#jayatma.com\")]), Storedge.Contact(fullName: \"Kayamuddin Ansari\", phones: \"7575801826\", emails: \"kayamuddin.ansari#jayatma.com\", imageDataAvailable: false, expanded: false, thumbnailImageData: 0 bytes, imageData: 0 bytes, contactType: 0, identifier: \"9D479A76-E092-4C9A-9BCC-418AB1DFC134\", namePrifix: \"\", givenName: \"Kayamuddin\", middleName: \"\", familyName: \"Ansari\", previousFamilyName: \"\", nameSuffix: \"\", nickName: \"\", organizationName: \"\", departmentName: \"\", jobTitle: \"\", phoneticGivenName: \"\", phoneticMiddleName: \"\", phoneticFamilyName: \"\", phoneticOrganizationName: \"\", note: \"\", birthday: isLeapMonth: false , nonGregorianBirthday: isLeapMonth: false , dates: [], postalAddresses: [], urlAddresses: [], contactRelations: [], socialProfiles: [], instantMessageAddresses: [], phoneNumbers: [Storedge.PhoneNumber(label: \"$!!$\", stringValue: \"7575801826\")], emailAddresses: [Storedge.Email(label: \"$!!$\", value: \"kayamuddin.ansari#jayatma.com\")]), Storedge.Contact(fullName: \"Manan Bhatt\", phones: \"7575801826\", emails: \"manan.bhatt#jayatma.com\", imageDataAvailable: false, expanded: false, thumbnailImageData: 0 bytes, imageData: 0 bytes, contactType: 0, identifier: \"0C1E052F-6636-4D47-979E-CFF2A66CF505\", namePrifix: \"\", givenName: \"Manan\", middleName: \"\", familyName: \"Bhatt\", previousFamilyName: \"\", nameSuffix: \"\", nickName: \"\", organizationName: \"\", departmentName: \"\", jobTitle: \"\", phoneticGivenName: \"\", phoneticMiddleName: \"\", phoneticFamilyName: \"\", phoneticOrganizationName: \"\", note: \"\", birthday: isLeapMonth: false , nonGregorianBirthday: isLeapMonth: false , dates: [], postalAddresses: [], urlAddresses: [], contactRelations: [], socialProfiles: [], instantMessageAddresses: [], phoneNumbers: [Storedge.PhoneNumber(label: \"$!!$\", stringValue: \"7575801826\")], emailAddresses: [Storedge.Email(label: \"$!!$\", value: \"manan.bhatt#jayatma.com\")])]"

Since your Contact is Codable you could utilize JSONEncoder/JSONDecoder and do the following:
if let json = try? JSONEncoder().encode(contact) {
userDefs?.setValue(json, forKey: "contact");
...
And to retrieve the Contact again:
if let loaded = userDefs?.value(forKey: "contact") as? Data {
let contact2 = try? JSONDecoder().decode(Contact.self, from: loaded)
...

Related

Sync mongodb database in aws 3 instance with each other

We are setting replica "rs0" in mongodb but show like this
We tried from last many days but not got proper solutions.
Replica configurations
rs0 [direct: primary] test> rs.config()
{
_id: 'rs0',
version: 17,
term: 66,
members: [
{
_id: 0,
host: 'ip-172-31-35-197.ec2.internal:27017',
arbiterOnly: false,
buildIndexes: true,
hidden: false,
priority: 1,
tags: {},
secondaryDelaySecs: Long("0"),
votes: 1
},
{
_id: 1,
host: '172.31.40.27:27017',
arbiterOnly: false,
buildIndexes: true,
hidden: false,
priority: 2,
tags: {},
secondaryDelaySecs: Long("0"),
votes: 1
},
{
_id: 2,
host: '172.31.38.235:27017',
arbiterOnly: false,
buildIndexes: true,
hidden: false,
priority: 3,
tags: {},
secondaryDelaySecs: Long("0"),
votes: 1
}
],
protocolVersion: Long("1"),
writeConcernMajorityJournalDefault: true,
settings: {
chainingAllowed: true,
heartbeatIntervalMillis: 2000,
heartbeatTimeoutSecs: 10,
electionTimeoutMillis: 10000,
catchUpTimeoutMillis: -1,
catchUpTakeoverDelayMillis: 30000,
getLastErrorModes: {},
getLastErrorDefaults: { w: 1, wtimeout: 0 },
replicaSetId: ObjectId("63ce58d964a80e070f6c2ee1")
}
}
Replica status
rs0 [direct: primary] test> rs.status()
{
set: 'rs0',
date: ISODate("2023-02-10T07:58:37.751Z"),
myState: 1,
term: Long("66"),
syncSourceHost: '',
syncSourceId: -1,
heartbeatIntervalMillis: Long("2000"),
majorityVoteCount: 1,
writeMajorityCount: 1,
votingMembersCount: 1,
writableVotingMembersCount: 1,
optimes: {
lastCommittedOpTime: { ts: Timestamp({ t: 1676015917, i: 40 }), t: Long("66") },
lastCommittedWallTime: ISODate("2023-02-10T07:58:37.695Z"),
readConcernMajorityOpTime: { ts: Timestamp({ t: 1676015917, i: 40 }), t: Long("66") },
appliedOpTime: { ts: Timestamp({ t: 1676015917, i: 40 }), t: Long("66") },
durableOpTime: { ts: Timestamp({ t: 1676015917, i: 40 }), t: Long("66") },
lastAppliedWallTime: ISODate("2023-02-10T07:58:37.695Z"),
lastDurableWallTime: ISODate("2023-02-10T07:58:37.695Z")
},
lastStableRecoveryTimestamp: Timestamp({ t: 1676015890, i: 35 }),
electionCandidateMetrics: {
lastElectionReason: 'electionTimeout',
lastElectionDate: ISODate("2023-02-09T06:40:25.035Z"),
electionTerm: Long("66"),
lastCommittedOpTimeAtElection: { ts: Timestamp({ t: 0, i: 0 }), t: Long("-1") },
lastSeenOpTimeAtElection: { ts: Timestamp({ t: 1675924812, i: 15 }), t: Long("65") },
numVotesNeeded: 1,
priorityAtElection: 1,
electionTimeoutMillis: Long("10000"),
numCatchUpOps: Long("0"),
newTermStartDate: ISODate("2023-02-09T06:40:25.038Z"),
wMajorityWriteAvailabilityDate: ISODate("2023-02-09T06:40:25.041Z")
},
members: [
{
_id: 0,
name: 'ip-172-31-35-197.ec2.internal:27017',
health: 1,
state: 1,
stateStr: 'PRIMARY',
uptime: 91105,
optime: { ts: Timestamp({ t: 1676015917, i: 40 }), t: Long("66") },
optimeDate: ISODate("2023-02-10T07:58:37.000Z"),
lastAppliedWallTime: ISODate("2023-02-10T07:58:37.695Z"),
lastDurableWallTime: ISODate("2023-02-10T07:58:37.695Z"),
syncSourceHost: '',
syncSourceId: -1,
infoMessage: '',
electionTime: Timestamp({ t: 1675924825, i: 1 }),
electionDate: ISODate("2023-02-09T06:40:25.000Z"),
configVersion: 17,
configTerm: 66,
self: true,
lastHeartbeatMessage: ''
},
{
_id: 1,
name: '172.31.40.27:27017',
health: 0,
state: 8,
stateStr: '(not reachable/healthy)',
uptime: 0,
optime: { ts: Timestamp({ t: 0, i: 0 }), t: Long("-1") },
optimeDurable: { ts: Timestamp({ t: 0, i: 0 }), t: Long("-1") },
optimeDate: ISODate("1970-01-01T00:00:00.000Z"),
optimeDurableDate: ISODate("1970-01-01T00:00:00.000Z"),
lastAppliedWallTime: ISODate("1970-01-01T00:00:00.000Z"),
lastDurableWallTime: ISODate("1970-01-01T00:00:00.000Z"),
lastHeartbeat: ISODate("2023-02-10T07:58:36.506Z"),
lastHeartbeatRecv: ISODate("1970-01-01T00:00:00.000Z"),
pingMs: Long("0"),
lastHeartbeatMessage: "replica set IDs do not match, ours: 63ce58d964a80e070f6c2ee1; remote node's: 63cfe6dc919add7e21a86867",
syncSourceHost: '',
syncSourceId: -1,
infoMessage: '',
configVersion: -1,
configTerm: -1
},
{
_id: 2,
name: '172.31.38.235:27017',
health: 0,
state: 8,
stateStr: '(not reachable/healthy)',
uptime: 0,
optime: { ts: Timestamp({ t: 0, i: 0 }), t: Long("-1") },
optimeDurable: { ts: Timestamp({ t: 0, i: 0 }), t: Long("-1") },
optimeDate: ISODate("1970-01-01T00:00:00.000Z"),
optimeDurableDate: ISODate("1970-01-01T00:00:00.000Z"),
lastAppliedWallTime: ISODate("1970-01-01T00:00:00.000Z"),
lastDurableWallTime: ISODate("1970-01-01T00:00:00.000Z"),
lastHeartbeat: ISODate("2023-02-10T07:58:36.502Z"),
lastHeartbeatRecv: ISODate("1970-01-01T00:00:00.000Z"),
pingMs: Long("0"),
lastHeartbeatMessage: "replica set IDs do not match, ours: 63ce58d964a80e070f6c2ee1; remote node's: 63cfe728bc3c837fff6957a5",
syncSourceHost: '',
syncSourceId: -1,
infoMessage: '',
configVersion: -1,
configTerm: -1
}
],
ok: 1,
'$clusterTime': {
clusterTime: Timestamp({ t: 1676015917, i: 40 }),
signature: {
hash: Binary(Buffer.from("0000000000000000000000000000000000000000", "hex"), 0),
keyId: Long("0")
}
},
operationTime: Timestamp({ t: 1676015917, i: 40 })
}
If we start 3 instances each other then service get 404 error in service because of database not synced with all instances.
Please help to solve this problem in aws instance mongodb database sync on 3 instances each other?

Mongoose pushing many documents into a document field

I'm trying to push many documents into a field to populate my mongo db, but for I keep getting the following error: SyntaxError: Invalid property id
This is the query I'm trying to do,
db.stripeproducts.findOneAndUpdate(
{ stripeProductId: 'prod_Ijq9Y1uiFV0bSl' },
{$push: {
bundlePhotoCodes:
{value: 'XFTYUONMBUNDLE', status: 'valid', validUntil: null, modelID: null },
{value: 'XFTYUONMBUNDLE', status: 'valid', validUntil: null, modelID: null },
{value: 'YIHH878BUNDLE', status: 'valid', validUntil: null, modelID: null},
{value: 'HSGYGVI8BUNDLE', status: 'valid', validUntil: null, modelID: null},
{value: 'HSGYGVI8BUNDLE', status: 'valid', validUntil: null, modelID: null},
{value: 'BMDUKKSBUNDLE', status: 'valid', validUntil: null, modelID: null},
{value: 'XFTYUONMBUNGTY', status: 'valid', validUntil: null, modelID: null },
{value: 'YIHH878BUNTRD', status: 'valid', validUntil: null, modelID: null},
{value: '88UJHDI8BUNRSD', status: 'valid', validUntil: null, modelID: null}
{value: 'HSGYGVI8BUNQSD', status: 'valid', validUntil: null, modelID: null},
{value: 'HSGYGVI8BUNDDF', status: 'valid', validUntil: null, modelID: null},
{value: 'BMDUKKSBUNDFFF', status: 'valid', validUntil: null, modelID: null}
}},
{upsert: true}
)
This is my schema:
const stripeProductSchema = new mongoose.Schema(
{
productName: String,
productPrice: Number,
productDescription: [{ type: String }],
productImage: String,
stripeProductId: String,
stripePriceId: String,
rate: String,
amount: String,
bundlePhotoCodes: [photoCodes],
modelPayment: {
type: Schema.Types.ObjectId,
ref: 'ModelPayment',
required: false,
},
},
{ strict: true, timestamps: true },
)
Your syntax is invald. To append multiple values to an array, you need to use $push with $each. For example:
db.stripeproducts.findOneAndUpdate(
{ stripeProductId: 'prod_Ijq9Y1uiFV0bSl' },
{
$push: {
bundlePhotoCodes: {
$each: [
{value: 'XFTYUONMBUNDLE', status: 'valid', validUntil: null, modelID: null},
{value: 'XFTYUONMBUNDLE', status: 'valid', validUntil: null, modelID: null},
...
]
}
}
},
{upsert: true}
)

Aggregation change value of a boolean to string

Have a collection with records , Need to convert boolean values of a column to string :
[
{
_id: "bmasndvhjbcw",
name: "lucas",
occupation: "scientist",
passed_phd: true,
age: 55,
location: "texas",
},
{
_id: "bmasndvhjbcx",
name: "mark",
occupation: "scientist",
age: 45,
passed_phd: true,
location: "texas",
},
{
_id: "bmasndvhjbca",
name: "stuart",
occupation: "lab assistant",
age: 25,
passed_phd: false,
location: "texas",
},
{
_id: "bmasndvhjbcq",
name: "cooper",
occupation: "physicist",
age: 69,
passed_phd: false,
location: "texas"
}
]
how to change boolean value of the records to string.
value that has true(boolean) in passed_phd should be converted to "yes"(string)
value that has false(boolean) in passed_phd should be converted to "no"(string)
[
{
_id: "bmasndvhjbcw",
name: "lucas",
occupation: "scientist",
passed_phd: "yes",
age: 55,
location: "texas",
},
{
_id: "bmasndvhjbcx",
name: "mark",
occupation: "scientist",
age: 45,
passed_phd: "yes",
location: "texas",
},
{
_id: "bmasndvhjbca",
name: "stuart",
occupation: "lab assistant",
age: 25,
passed_phd: "no",
location: "texas",
},
{
_id: "bmasndvhjbcq",
name: "cooper",
occupation: "physicist",
age: 69,
passed_phd: "no",
location: "texas"
}
]
mongodb version 4.0
.
The $cond aggregation pipeline operator can do this.
Beginning with MongoDB 4.2, these can be used in an update or in an aggregation pipeline, like:
db.collection.aggregate([
{$set:{
passed_phd:{
$cond:{
if:"$passed_phd",
then:"yes",
else:"no"
}
}
}}
])

Updating 3rd tier document in subarray

I have a document as follows (in a Projects collection):
title: "title"
company: "company"
companyID: "companyID"
category: "category"
starred: false
createdAt: new Date
tasks: [
{
task:'something'
completed: false
taskID: Random.id()
}
{
task:'something'
completed: false
taskID: Random.id()
}
{
task:'something'
completed: false
taskID: Random.id()
}
]
I can set completed: true on a task using this method:
completeTask: (projectID, taskID, ifCompleted) ->
Projects.update {
_id: projectID
'tasks.taskID': taskID
}, $set: 'tasks.$.completed': ifCompleted
return
if I change my document to this:
{
title: 'title.com'
company: 'company'
companyID: Random.id()
category: 'category'
starred: false
createdAt: new Date
categories: [
{
completed: true
name: 'ideas'
_id: Random.
tasks: [
{task: 'something', completed: false, taskID: Random.id()}
{task: 'something', completed: false, taskID: Random.id()}
{task: 'something', completed: false, taskID: Random.id()}
]
}
{
completed: false
name: 'development'
_id: Random.id()
tasks: [
{task: 'something', completed: false, taskID: Random.id()}
{task: 'something', completed: false, taskID: Random.id()}
{task: 'something', completed: false, taskID: Random.id()}
]
}
]
}
how can I set completed: true on a task?
So far I have
completeTask: (projectID, categoryID, taskID, ifCompleted) ->
Projects.update {

How to create an object of objects in CoffeeScript?

I am trying to create an objects which consist of other objects. I can't figure out the syntax though. I read the Little Book on CoffeeScript but it does not say what to do in this situation. I tried the following syntaxes but can't get it right:
objectOfHomes = {
{
location: "Paris Island", age: 18
}
}
objectOfHomes:
{location: "Paris Island", age: 18},
{location: "29 Palms", age: 18},
{location: "Camp Lejeune", age: 19},
{location: "Iraq", age: 20},
{location: "Camp Lejeune", age: 20},
{location: "Mesa Verda", age: 22}
objectOfHomes =
{location: "Paris Island", age: 18}
{location: "29 Palms", age: 18}
{location: "Camp Lejeune", age: 19}
{location: "Iraq", age: 20}
{location: "Camp Lejeune", age: 20}
{location: "Mesa Verda", age: 22}
In coffeescript you could do it like this:
objectOfHomes:
a:
location: "Paris Island"
age: 18
You are likely better off using an array of objects than on object of objects, unless you have a primary key of some sort which you do not appear to have.
objectOfHomes = [
{location: "Paris Island", age: 18}
{location: "29 Palms", age: 18}
{location: "Camp Lejeune", age: 19}
{location: "Iraq", age: 20}
{location: "Camp Lejeune", age: 20}
{location: "Mesa Verda", age: 22}
]
You need to include key values with your objects:
objectOfHomes:
a: {location: "Paris Island", age: 18}
b: {location: "29 Palms", age: 18}
c: {location: "Camp Lejeune", age: 19}
d: {location: "Iraq", age: 20}
e: {location: "Camp Lejeune", age: 20}
f: {location: "Mesa Verda", age: 22}