Enyo different collection with same model kind - javascript

I have been trying to create two collection with a common model kind. I am getting the following error:
"Uncaught enyo.Store.addRecord: duplicate record added to store for kind app.ImageModel with primaryKey set to id and the same value of 67774271 which cannot coexist for the kind without the ignoreDuplicates flag of the store set to true ".
Following are the two collection i have defined...
enyo.kind({
name: "app.FeatureCollection",
kind: "enyo.Collection",
model: "app.ImageModel",
defaultSource: "appF",
...
...
});
enyo.kind({
name: "app.SearchCollection",
kind: "enyo.Collection",
model: "app.ImageModel",
defaultSource: "appS",
...
...
});
And the model which i am using is as follows:
enyo.kind({
name: "app.ImageModel",
kind: "enyo.Model",
readOnly: true,
....
....
});
At one point i am setting like this:
this.set("data", new app.FeatureCollection());
and in another,
this.set("data", new app.SearchCollection());
I am not able to find out what could generate the error. I even tried to set "ignoreDuplicates" to true in model...but still the error comes. Any suggestion where i could be going wrong.

The ignoreDuplicates flag is expected to be set on enyo.Store and not enyo.Model:
enyo.store.ignoreDuplicates = true;
Are you using the fetch method of enyo.Collection to retrieve your data? If so, you might consider setting the strategy property to merge in your fetch call so that you have a single record for each unique image from your dataset, i.e.:
myCollection.fetch({strategy: "merge", success: function(rec, opts, res) {
// do something after data is retrieved
}});

I'm not seeing a problem with the pieces of code you provided. I created a sample on jsFiddle and it works as expected.
http://jsfiddle.net/z7WwZ/
Maybe the issue is in some other part of your code?
enyo.kind({
name: "app.FeatureCollection",
kind: "enyo.Collection",
model: "app.MyModel"
});
enyo.kind({
name: "app.SearchCollection",
kind: "enyo.Collection",
model: "app.MyModel"
});
enyo.kind({
name: "app.MyModel",
kind: "enyo.Model",
readOnly: true,
defaults: {
firstName: "Unknown",
lastName: "Unknown"
}
});
enyo.kind({
name: "App",
components: [],
bindings: [],
create: enyo.inherit(function (sup) {
return function () {
sup.apply(this, arguments);
this.collection1 = new app.FeatureCollection(this.data1);
enyo.log("Collection1(0) >>> " + this.collection1.at(0).get("lastName"));
this.collection1.at(0).set("lastName", "Smith");
enyo.log("Collection1(0) >>> " + this.collection1.at(0).get("lastName"));
this.collection2 = new app.SearchCollection(this.data2);
enyo.log("Collection2(0) >>> " + this.collection2.at(0).get("lastName"));
this.collection1.at(0).set("lastName", "Jones");
enyo.log("Collection2(0) >>> " + this.collection1.at(0).get("lastName"));
};
}),
data1: [{
firstName: "Hall",
lastName: "Caldwell"
}, {
firstName: "Felicia",
lastName: "Fitzpatrick"
}, {
firstName: "Delgado",
lastName: "Cole"
}],
data2: [{
firstName: "Alejandra",
lastName: "Walsh"
}, {
firstName: "Marquez",
lastName: "James"
}, {
firstName: "Barr",
lastName: "Lott"
}]
});
new App().renderInto(document.body);

Related

Mongoose populate referencing object id, not the object itself

Background
Here's part of my User model:
const Group = require("./Group")
...
groups: {
type: [{ type: Schema.ObjectId, ref: Group }],
default: [],
},
And here's my Group model:
module.exports = mongoose.model(
"Group",
new Schema(
{
name: {
type: String,
required: true,
unique: true,
},
/**
* Array of User ObjectIDs that have owner rights on this group
*/
owners: {
type: [{ type: Schema.ObjectId, ref: User }],
default: [],
},
},
{
timestamps: true,
}
)
)
The Code
Here's the code I'm running to try and populate:
const user = await (await User.findOne({ _id: ... })).execPopulate("Group")
console.log(user.groups)
My console.log is outputting an array of object IDs, when I'd like it to output an actual Group document.
Attempted solutions
I've tried changing my ref to be using the string ("Group"), I've tried arranging my query differently, etc. I'm not sure how I'd go about doing this.
Apologies in advance if this is a duplicate, I've done my best to search but can't really find a solution that works for me.
Specifically, what do I need help with?
I'm trying to create a 'link' between a user model and a group model. In my console.log, I expect it to output a Group document; but it outputs an object ID (which is how it's stored raw in the database, meaning that Mongoose isn't transforming it correctly)
When you change execPopulate to populate like:
async function findUserAndPopulate(userId){
const response = await User.findOne({
_id: userId,
}).populate('groups')
console.log("response",response)
}
You got:
{
groups: [
{
owners: [Array],
_id: 5ecc637916a2223f15581ec7,
name: 'Crazy',
createdAt: 2020-05-26T00:31:53.379Z,
updatedAt: 2020-05-26T00:31:53.379Z,
__v: 0
}
],
_id: 5ecc6206820d583b99b6b595,
fullname: 'James R',
createdAt: 2020-05-26T00:25:42.948Z,
updatedAt: 2020-05-26T00:36:12.186Z,
__v: 1
}
So you can access the user.groups
See the doc: https://mongoosejs.com/docs/populate.html

Generate valid v-model value using dot notation string as object reference to the data

Basically i've made proyxy-component which renders different components based on what the :type is and it works great. The point is that I create a schema of the form controls and a separate data object where the data from the form controls is stored. Everything is working good but i have a problem when formData object contains nested objects.
In my example test.test1
How can i make the v-model value dynamic which is generated based on what the string is.
My Compoennt
<proxy-component
v-for="(scheme, index) in personSchema.list"
:key="index"
:type="scheme.type"
:props="scheme.props"
v-model="formData[personSchema.prefix][scheme.model]"
v-validate="'required'"
data-vv-value-path="innerValue"
:data-vv-name="scheme.model"
:error-txt="errors.first(scheme.model)"
></proxy-component>
Data
data() {
return {
selectOptions,
formData: {
person: {
given_names: '',
surname: '',
sex: '',
title: '',
date_of_birth: '',
place_of_birth: '',
nationality: '',
country_of_residence: '',
acting_as: '',
test: {
test1: 'test',
},
},
},
personSchema: {
prefix: 'person',
list: [
{
model: 'given_names',
type: 'custom-input-component',
props: {
title: 'Name',
},
},
{
model: 'surname',
type: 'custom-input-componentt',
props: {
title: 'Surname',
},
},
{
model: 'test.test1',
type: 'custom-input-component',
props: {
title: 'test 1',
},
},
{
model: 'sex',
type: 'custom-select-component',
props: {
title: 'Sex',
options: selectOptions.SEX_TYPES,
trackBy: 'value',
label: 'name',
},
},
],
},
};
},
I would recomment you to write a vue-method (under the data section) that returns the object for v-model
v-model="resolveObject(formData[personSchema.prefix][scheme.model])"
or
v-model="resolveObject([personSchema.prefix] , [scheme.model])"
There you can do handle the dot-notation and return the proper nested property.
I don't think it's possible directly with v-model, you can take a look at:
https://v2.vuejs.org/v2/guide/reactivity.html
Maybe the best solution would be use a watch (deep: true) as a workaround.
(I would try first to use watch properties inside formData[personSchema.prefix][scheme.model].)

How to save form data as an objects and array of objects to mongodb using loop in node.js?

I am new to MongoDB, I am using Node.js, Express 4 and mongoose(mongoDB) for my project.I stuck to save form data to mongoDB within loop and my model contains Objects and array of objects as well.
Model :
var Subscriber = new Schema({
first_name: String,
emergency_contact_1: {
name: String,
number: [{
type: String
}]
},
residential: {
phone: String,
address: String,
...
},
medications: [
{
visit_id: { type: Object },
name: String,
....
}],
food_allergies: [
{type: String}
],
....
});
Controller :
I want to save data in this way:
var subscriber = new Subscriber();
//Here I am trying to save all form's fields to mongoBD fields.
for (var field in form_data) {
subscriber[field] = form_data[field];
}
subscriber.save(function (err1, instance) {
if (err) {
console.log("error");
return res.send("...");
}
console.log("saved successfully");
}
Normal fields are getting saved properly using above loop but when objects or arrays came then it won't get save to mongoDB.
Any solution ? or any other way to insert/save data through loop to mongoDB model ?
Any help would be appreciated.Thank you..!!
Nodejs
var PersonSchema = new Schema({
name: {
given: {
type: String,
required: true
},
family: {
type: String,
required: true
}
},
children: [PersonSchema]
});
var Person = mongoose.model('Person', PersonSchema);
app.post('/person', function (req, res) {
Person.create(req.body)
.then(function (created) {
console.log(created);
res.json(created.id);
});
});
Client
$.ajax({
url: '/person',
type: 'POST',
data: {
name: {
family: 'Green'
},
children: [{
name: {
given: 'Matt',
family: 'Green'
}
}, {
name: {
given: 'Dave',
family: 'Green'
}
}]
}
})
As you can see, I have nested objects and arrays. This works fine for me :)

Update nested array in Meteor

This is my schema:
{
_id: "FJwSEMdDriddXLKXh"
name: "t"
number: "5"
owners: [
{
_id: 1,
name: "Name",
address: "Address",
type: "Type",
gender: "Gender",
notes: []
}
]
}
and on click I would add fields inside owners nested notes array.
This is my Meteor template events:
Template.owners.event({
'click #addNoteToOwner' : function(event, template){
event.preventDefault();
Territories.update({_id: template.data._id, owners: this._id}, {$push : {'owners.$.notes': {title:"First Title"}}})
}
})
If I try to update the doc, the following console errorT appear:
Uncaught Error: Not permitted. Untrusted code may only update documents by ID. [403]
Is my syntax correct? How can I update this nested array?
Thanks!
There is mistake in your query in owners field:
Territories.update({
_id: template.data._id,
owners: {
$elemMatch: {
_id: this._id
}
},
{
$push: {
'owners.$.notes': {
title: "First Title"
}
}
})
You won't be able to update directly from client side, because you use owners field and only _id is allowed. To solve this you can update using Meteor.methods and call that method from client side.

Backbone.js adding to Collection

In Backbone, I have a collection which is populated with some JSON data which looks like below.
[
{
"test1": {
"fistName": "test",
"lastName": "example"
},
"test2": {
"fistName": "test",
"lastName": "example"
}
},
{
"test1": {
"fistName": "test",
"fistName": "example"
},
"test2": {
"fistName": "test",
"fistName": "example"
}
},
]
Currently im trying to add a new model to the collection holding data like the above.
This is the model.
Test = Backbone.Model.extend({
defaults : {
test1: {
firstName: null,
lastName: null
},
test2: {
firstName: null,
lastName: null
}
},
});
Below is what I am trying
var test = new Test({test1: {firstName: $("#test1 option:selected").val(), score: $("#test1lastName").val()}}, {test2: {firstName: $("#test2 option:selected").val(), score: $("#test2lastName").val()}});
myCollection.add(test);
However doing this only populates test1 data and not test2 data. What would be the correct way to add both test1 and test2 data into the model, which could then be added to the collection.
Thanks
UPDATE
Just to clarify, test 1 and 2 are not separate objects, they are relevant to each other and need to be in the same model
Edit, depending on how your model is defined, if you format it as below you might able to debug a little better.
var test = new TFS.Test({
test1: {
firstName: $("#test1 option:selected").val(),,
lastName: '', // code for last name?
score: $("#test1lastName").val()
},
test2: {
firstName: $("#test2 option:selected").val(),
lastName: '',
score: $("#test2lastName").val()
}
});
myCollection.add(test);
I might be able to offer you a little more help if you give a better view of the entire action/process - i.e. what is triggering the creation of these models? Could there be a problem with jQuery, and your document not being ready?

Categories