Why am I unable to spread an object in my mongoose model? - javascript

This might be a silly question but why on earth am I getting an "Unexpected token" error for the following code snippet? Bear in mind it is a mongoose model.
Error message
SyntaxError: D:/Coding/Species Project/backend/models/species.js: Unexpected token (15:2)
13 | },
14 | organism: {
> 15 | ...shared,
| ^
16 | enum: ["Plant", "Animal", "Other"],
17 | },
18 | taxonomy: {
Mongoose model
const shared = {
type: String,
required: true,
}
const SpeciesSchema = new Schema({
name: {
common: shared,
scientific: shared,
},
organism: {
...shared,
enum: ["Plant", "Animal", "Other"],
},
...,
}

Spread operator is used as parameters from array.
You might want to use this, instead
const SpeciesSchema = new Schema({
name: {
common: shared,
scientific: shared,
},
organism: Object.assign({}, shared, enum: ["Plant", "Animal", "Other"]},
...,
}

Related

Maximum call stack size exceeded when filtering objects with inverse relationship ( Realm 10.1.1 )

Giving the following schema:
const Person = {
name: "User",
primaryKey: "_id",
properties: {
_id: "objectId",
name: "string",
age: "number",
company: "Company[]"
}
};
const Company = {
name: "Company",
primaryKey: "_id",
properties: {
_id: "objectId",
name: "string",
boss: {
type: 'linkingObjects',
objectType: 'Person',
property: 'company'
}
}
};
After adding some persons and several of them with a company, I try to filter by age and get the ones that are over 30 years with the code realm.objects("Person").filtered("age > 30");
The result of this query is the following error:
Maximum call stack size exceeded.
I expect to have a list of Persons which meets the requirement, but instead I have this error. I have seen that in the release 10.0.0 this error is suppose to be fix for toJSON() function. If I try to filter the object by its id everything works fine, but once I try to get a list of some objects I get this error.
Does somebody have a solution for this?
I´m using -->
Realm: 10.1.1
React Native: 0.62.2
Node: 10.22.1

Assigning an object of flow type SuperType to SubType causes error

I was under the impression that an inexact object type in Flow can be supplied an object with properties not declared in the type as long as all the properties that have been declared in the type are present.
An inexact object type declaration in Flow indicates that "the object can have any of these properties, plus any more unspecified". So an object of type SubType should be able to be assigned an object of type SuperType and still be valid.
What am I missing here?
I believe it has something to do with nested object types, but if I can't modify the undeclared properties on the genericPlan (SubType) why should it matter?
/* #flow */
type SuperType = {
plan: {
id: string,
location: {
id: string,
team: {
id: string,
},
},
},
};
type SubType = {
plan: {
id: string,
location: {
id: string,
},
},
};
const planWithTeam: SuperType = {
plan: {
id: '',
location: {
id: '',
team: {
id: '',
},
},
},
};
// The following throws this error:
// Cannot assign planWithTeam to genericPlan because property team is
// missing in SubType [1] but exists in SuperType [2] in property plan.location.
const genericPlan: SubType = planWithTeam;
No, nested object props are invariant by default. To make in covariant just add a plus sign:
type SubType = {
+plan: {
id: string,
+location: {
id: string,
},
},
};
Try

Mongoose + MongoDB - Cast to ObjectID failed for value after try save with POSTMAN

I'm trying to save an object that references other 2 objects in mongoDB, but I'm not getting it. Whenever I try, I get this message.
For this, this using POSTMAN to test the API that I am creating.
{
"message": "Order validation failed: payments.0.credit_card.card: Cast to ObjectID failed for value \"{ number: '4898308633754712',\n holder_name: 'Test test',\n exp_month: 1,\n exp_year: 2022,\n cvv: '1234' }\" at path \"credit_card.card\", customer: Cast to ObjectID failed for value \"{ name: 'Test Test', email: 'test#gmail.com' }\" at path \"customer\""
}
The json object I'm trying to save in mongoDB:
{
"items": [{
"name": "Plano s",
"amount": 12345,
"description": "Descrição do Plano Sanarflix",
"quantity": 1
}],
"customer": {
"name": "Test Test",
"email": "test#gmail.com"
},
"payments": [{
"payment_method": "credit_card",
"credit_card": {
"installments":1,
"capture": true,
"card": {
"number": "4898308633754712",
"holder_name": "Test Test",
"exp_month": 1,
"exp_year": 2022,
"cvv": "1234"
}
}
}]
}
This is the model order I defined:
'use strict';
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
// Model for order
const schema = new Schema({
customer: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Customer',
required: function(){
return this.customer_id;
}
},
items: [{
amount: {
type: Number,
required: true
},
description: {
type: String,
trim: true
},
quantity: {
type: Number,
required: true
}
}],
payments: [{
payment_method: {
type: String,
required: true,
trim: true
},
credit_card: {
installments: {
type: Number,
default: 1
},
capture: {
type: Boolean,
default: true
},
card: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Card'
}
},
}]
});
module.exports = mongoose.model('Order', schema);
What is wrong with it? Because when I import the same json to MongoDB with Studio3 Mongo Manager, I can save it and see the object in the correct way.
an object that references other 2 objects, yes, ObjectId does references, yet you're passing the whole objects.
Three options:
pass the id of customer and card objects (if they exist already)
insert these new data in their respective collections then insert your order using the created IDs (likely the solution)
rewrite your schema to have only the Order collection that would hold everything (not really great).
Also, having card numbers transiting through your server is really dangerous (legally speaking), especially if you're to store them... check out how the payment service you're implementing handles transactions: on any decent service the server never sees banking data, discharging your company of any liability.

How does Reflexive association work in SAILS JS?

Here is my User model: I am trying to create a reflexive association among users. Mentors and mentees
fullName: {
type: 'string',
required: true,
description: 'Full representation of the user\'s name',
maxLength: 120,
example: 'Lisa Microwave van der Jenny'
},
typeOfUser: {
required: true,
type: 'string',
example: 'mentor',
description: 'The user\'s type of account.',
},
skills:{
collection:'skills',
via: 'userId'
},
mentees:{
collection: 'user',
via: 'mentors'
},
mentors:{
collection:'user',
via: 'mentees'
}
Here is my code.
// Add mentor of mentorId as the mentor of currentUser
await User.addToCollection(3, 'mentor',8);
// Find mentor and populate mentees
var showMentee = await User.findOne(8).populate('mentee');
The Response is correct:
{
"mentee": [
{
"id": 3,
"fullName": "1234",
"typeOfUser": "mentee"
}
],
"id": 8,
"fullName": "1234",
"typeOfUser": "mentor"
}
But the problem is with the association table that sails has created:
+----+-------------+-------------+
| id | user_mentee | user_mentor |
+----+-------------+-------------+
| 1 | 8 | 3 |
| 2 | 8 | 3 |
+----+-------------+-------------+
I can not understand the column naming in this case. The mentor id is 8 and mentee id is 3, but it is showing opposite.

Error when using $addToSet and $each, Mongo and Node JS

I am trying to use $addToSet to add a array of Strings to a MongoDB.
The Object setup is as defined:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
module.exports = mongoose.model('Company', {
License: { type: String, index: true },
"Classifications": [
{
Classification: { type: String, _id: false }
}
]
});
The current object looks like this in Mongo:
{
"_id": {
"$oid": "55b03f9337b46f10d38843d7"
},
"Classifications": [
"A - GENERAL ENGINEERING CONTRACTOR",
"B - GENERAL BUILDING CONTRACTOR",
"C12 - EARTHWORK AND PAVING"
],
"License": "CA_*****"
}
I am trying to run $addToSet on the following array:
var classifications = [ 'B - GENERAL BUILDING CONTRACTOR',
'C10 - ELECTRICAL',
'C33 - PAINTING AND DECORATING',
'C29 - MASONRY',
'C-9 - DRYWALL',
'C54 - TILE (CERAMIC AND MOSAIC)',
'C-5 - FRAMING AND ROUGH CARPENTRY',
'C20 - WARM-AIR HEATING, VENTILATING AND AIR-CONDITIONING',
'C36 - PLUMBING',
'C39 - ROOFING' ]
Company.update({ '_id': company._id }, { $addToSet: { "Classifications": { $each: classifications } } }
When I run Company.update in Node, I am getting the error
[TypeError: Cannot use 'in' operator to search for '_id' in C39 -
ROOFING]
Any idea why this is happening?
Finally figured out my issue.
In the Schema I had:
"Classifications": [
{
Classification: { type: String, _id: false }
}
]
Which was looking for a object with a String in it. The Schema should of just been:
"Classifications": [String]
Which allows for
Company.update({ '_id': company._id }, { $addToSet: { "Classifications": { $each: classifications } } }
to run and add the strings from the array with no issue

Categories