In a suitelet sublist ,how to populate saved searches with an edit | view column for each row? - netsuite

here i have two scripts one is suitelet other one is client script .
Please forgive me for the silly mistake as I have not much knowledge in netsuite.
/**
*#NApiVersion 2.x
*#NScriptType Suitelet
*/
define(['N/record','N/ui/serverWidget','N/redirect','N/runtime','N/search'],function(record,serverWidget,redirect,runtime,search){
function onRequest(context){
var Request = context.request;
var Response = context.response;
if(Request.method == 'GET') {
var form=serverWidget.createForm({title:"Customer entry Suitelet"});
var primaryinfo=form.addFieldGroup({
label:'Primary Information',
id:'custpage_advs_primary_info',
});
var firstname=form.addField({
label:'First Name',
id:'custpage_advs_first_name',
type:serverWidget.FieldType.TEXT,
container:'custpage_advs_primary_info'
});
firstname.isMandatory=true;
var lastname=form.addField({
label:'Last Name',
id:'custpage_advs_last_name',
type:serverWidget.FieldType.TEXT,
container:'custpage_advs_primary_info'
});
lastname.isMandatory=true;
var email=form.addField({
label:'Email',
id:'custpage_advs_email',
type:serverWidget.FieldType.EMAIL,
container:'custpage_advs_primary_info'
});
email.isMandatory=true;
var phone=form.addField({
label:'Phone',
id:'custpage_advs_phone',
type:serverWidget.FieldType.PHONE,
container:'custpage_advs_primary_info'
});
var mysublist = form.addSublist({
id: 'custpage_advs_sublistid',
type: serverWidget.SublistType.LIST,
label:'My Sublist'
});
mysublist.addField({
id: 'custpage_advs_sublist_internalid',
type: serverWidget.FieldType.INTEGER,
label: 'Internal Id'
});
mysublist.addField({
id: 'custpage_advs_sublist_fullname',
type: serverWidget.FieldType.TEXT,
label: 'Name'
});
mysublist.addField({
id: 'custpage_advs_sublist_fname',
type: serverWidget.FieldType.TEXT,
label: 'First Name'
});
mysublist.addField({
id: 'custpage_advs_sublist_lname',
type: serverWidget.FieldType.TEXT,
label: 'Last Name'
});
mysublist.addField({
id: 'custpage_advs_sublist_email',
type: serverWidget.FieldType.EMAIL,
label: 'Email'
});
mysublist.addField({
id: 'custpage_advs_sublist_phone',
type: serverWidget.FieldType.PHONE,
label: 'Phone'
});
mysublist.addField({
id: 'custpage_advs_sublist_view',
type: serverWidget.FieldType.URL,
label: 'VIEW'
});
var submit=form.addSubmitButton({
id : 'custpage_advs_submit_record',
label : 'Submit'
});
Response.writePage(form);
// form.clientScriptModulePath = './advs_cs_populatesublisttask.js';
form.clientScriptFileId = 91370;
var fnameValue = Request.parameters.custparam_first_name;
var lnameValue = Request.parameters.custparam_last_name;
var emailValue = Request.parameters.custparam_email;
var phoneValue = Request.parameters.custparam_phone;
log.debug("param from clientScript "+fnameValue);
if(fnameValue){
firstname.defaultValue =fnameValue;
// form.clientScriptFileId = 91370;
var fnameValue = Request.parameters.custparam_first_name;
var lnameValue = Request.parameters.custparam_last_name;
var emailValue = Request.parameters.custparam_email;
var phoneValue = Request.parameters.custparam_phone;
var fnamecustomerSearch = search.create({
type:'customrecord_advs_customer_entry_form',
filters:['custrecord_advs_first_name',"startswith",fnameValue],
columns:[
search.createColumn({name: "name"}),
search.createColumn({name: "custrecord_advs_first_name"}),
search.createColumn({name: "custrecord_advs_last_name"}),
search.createColumn({name: "custrecord_advs_email"}),
search.createColumn({name: "custrecord_advs_phone"}),
search.createColumn({name: "internalid"}),
search.createColumn({name: "id"})
]
});
var counter = 0;
fnamecustomerSearch.run().each(function(result) {
log.debug("my result", +result);
var oldfullname = result.getValue('name');
var InternalidVal = result.getValue('internalid');
var firstname=result.getValue('custrecord_advs_first_name');
var lastname=result.getValue('custrecord_advs_last_name');
var email=result.getValue('custrecord_advs_email');
var phone=result.getValue('custrecord_advs_phone');
// var view=result.getValue('view');
var view= result.getValue('edit|view');
log.debug("view is"+view);
mysublist.setSublistValue({
id: 'custpage_advs_sublist_internalid',
line: counter,
value: InternalidVal
});
mysublist.setSublistValue({
id: 'custpage_advs_sublist_fullname',
line: counter,
value:oldfullname
});
mysublist.setSublistValue({
id: 'custpage_advs_sublist_fname',
line: counter,
value: firstname
});
mysublist.setSublistValue({
id: 'custpage_advs_sublist_lname',
line: counter,
value: lastname
});
mysublist.setSublistValue({
id: 'custpage_advs_sublist_email',
line: counter,
value: email
});
mysublist.setSublistValue({
id: 'custpage_advs_sublist_phone',
line: counter,
value:phone
});
counter++;
return true;
});
}
}
return true;
}
else
{
var Fname= Request.parameters.custpage_advs_first_name;
var Lname=Request.parameters.custpage_advs_last_name;
var Email=Request.parameters.custpage_advs_email;
var Phone=Request.parameters.custpage_advs_phone;
var Fullname=Fname+' '+Lname;
var customRecord=record.create({
type:'customrecord_advs_customer_entry_form',
isDynamic:true,
});
customRecord.setValue({
fieldId:'name',
value:Fullname
});
customRecord.setValue({
fieldId:'custrecord_advs_first_name',
value:Fname
});
customRecord.setValue({
fieldId:'custrecord_advs_first_name',
value:Lname
});
customRecord.setValue({
fieldId:'custrecord_advs_email',
value:Email
});
customRecord.setValue({
fieldId:'custrecord_advs_phone',
value:Phone
});
var recordId=customRecord.save({
enableSourcing: false,
ignoreMandatoryFields: false
});
redirect.toSuitelet({
scriptId: 'customscript_advs_ss_customersuitelet',
deploymentId: 'customdeploy_advs_ss_customersuitelet',
});
}
}
return{
onRequest:onRequest
}
});
and then I added some conditions in client scripts .
but all I need is to add an edit/ view column in my suitelet
FYR
here is my client script
/**
* #NApiVersion 2.0
* #NScriptType ClientScript
*/
define(['N/currentRecord','N/search','N/record','N/url'],function(currentRecord,search,record,url){
function fieldChanged(context) {
var recordObj=context.currentRecord;
var name = context.fieldId;
if (name == 'custpage_advs_first_name'){
var fnameValue=recordObj.getValue({
fieldId:'custpage_advs_first_name'
});
alert("First name that you have entered is " +fnameValue);
var suiteUrl = url.resolveScript({
scriptId: 'customscript_advs_ss_populatesublisttask',
deploymentId: 'customdeploy_advs_ss_populatesublisttask',
returnExternalUrl:false,
params : {
custparam_first_name : fnameValue, //define a parameter and pass the value to it
}
});
}
}
else{
return true;
}
setWindowChanged(window,false);
window.location = suiteUrl;
}
return{
fieldChanged:fieldChanged
}
});
I guess I'm mostly just looking for a high level answer, because I'm not sure I'm even approaching this correctly.

You should reduce the code you paste in your question to the parts that isolate the problem.
To solve your issue, add a new field of type INLINEHTML.
sublist.addField({
id: 'YOUR_ID',
label: 'YOUR_LABEL',
type: serverWidget.FieldType.INLINEHTML
})
For each line, set the value to a link using regular html anchor tags.
const view_url = url.resolveRecord({
recordType: TYPE
recordId: ID,
isEditMode: false
})
const edit_url = url.resolveRecord({
recordType: TYPE
recordId: ID,
isEditMode: true
})
sublist.setSublistValue({
line: LINE,
id: 'YOUR_ID',
value: `view / edit`
})

Related

How to do search filter criteria in a suitelet?

here is my suitelet. I am also getting the condition error.
without giving the dates, it directly goes into the condition, and it is giving me an error called ""SSS_INVALID_SRCH_FILTER". yes I know this error why it is coming. this error because it has no value why it is happening means As soon as the suitelet loading itself, it is directly going into the condition. how should it be?
/**
*#NApiVersion 2.x
*#NScriptType Suitelet
*/
define(['N/record','N/ui/serverWidget','N/redirect','N/runtime','N/search','N/url'],function(record,serverWidget,redirect,runtime,search,url){
function onRequest(context){
var Request = context.request;
var Response = context.response;
var name = context.fieldId;
if(Request.method == 'GET') {
var form=serverWidget.createForm({title:"Customer entry Suitelet"});
var primaryinfo=form.addFieldGroup({
label:'Primary Information',
id:'custpage_advs_primary_info',
});
var firstname=form.addField({
label:'First Name',
id:'custpage_advs_first_name',
type:serverWidget.FieldType.TEXT,
container:'custpage_advs_primary_info'
});
firstname.isMandatory=true;
var lastname=form.addField({
label:'Last Name',
id:'custpage_advs_last_name',
type:serverWidget.FieldType.TEXT,
container:'custpage_advs_primary_info'
});
lastname.isMandatory=true;
var startdate=form.addField({
label:'Start Date',
id:'custpage_advs_start_date',
type:serverWidget.FieldType.DATE,
container:'custpage_advs_primary_info'
});
var enddate=form.addField({
label:'End Date',
id:'custpage_advs_end_date',
type:serverWidget.FieldType.DATE,
container:'custpage_advs_primary_info'
});
var submit=form.addSubmitButton({
id : 'custpage_advs_submit_record',
label : 'Submit'
});
Response.writePage(form);
form.clientScriptFileId = 91375;
var fnameValue = Request.parameters.custparam_first_name;
var lnameValue = Request.parameters.custparam_last_name;
if(fnameValue){
var fnamecustomerSearch = search.create({ //style="text-align:right"
type:'customrecord_advs_customer_entry_form',
filters:['custrecord_advs_first_name',"startswith",fnameValue],
columns:[
search.createColumn({name: "name"}),
search.createColumn({name: "custrecord_advs_first_name"}),
search.createColumn({name: "custrecord_advs_last_name"}),
search.createColumn({name: "id"}),
search.createColumn({name:"created"})
]
});
var counter = 0;
fnamecustomerSearch.run().each(function(result) {
var InternalidVal = result.getValue('internalid');
var firstname=result.getValue('custrecord_advs_first_name');
var lastname=result.getValue('custrecord_advs_last_name');
var recordid=result.id;
const view_url = url.resolveRecord({
recordType:'customrecord_advs_customer_entry_form',
recordId: recordid,
isEditMode: false
});
mysublist.setSublistValue({
id: 'custpage_advs_sublist_internalid',
line: counter,
value: InternalidVal
});
mysublist.setSublistValue({
id: 'custpage_advs_sublist_fname',
line: counter,
value: firstname
});
mysublist.setSublistValue({
id: 'custpage_advs_sublist_lname',
line: counter,
value: lastname
});
mysublist.setSublistValue({
line: counter,
id: 'custpage_advs_sublist_view',
value:"<html lang='en'><head> <style> a {color:#ff0000; background-color: transparent; text-decoration: none;}</style></head><body><a href='"+view_url+"' target='blank'> View</a></body></html>"
});
counter++;
return true;
});
}
else if((startdate)&&(enddate)){
var datecustomerSearch = search.create({
type:'customrecord_advs_customer_entry_form',
filters:[
["created","onorafter","09/12/2022"],
'and',
["created",'before',"17/12/2022"],
'and',
['mainline',"is",true]
],
columns:[
search.createColumn({name: "custrecord_advs_first_name"}),
search.createColumn({name: "custrecord_advs_last_name"}),
search.createColumn({name: "id"}),
search.createColumn({name:"created"})
]
});
var counter = 0;
datecustomerSearch.run().each(function(result) {
var InternalidVal = result.getValue('internalid');
var firstname=result.getValue('custrecord_advs_first_name');
var lastname=result.getValue('custrecord_advs_last_name');
var recordid=result.id;
const view_url = url.resolveRecord({
recordType:'customrecord_advs_customer_entry_form',
recordId: recordid,
isEditMode: false
});
mysublist.setSublistValue({
id: 'custpage_advs_sublist_internalid',
line: counter,
value: InternalidVal
});
mysublist.setSublistValue({
id: 'custpage_advs_sublist_fname',
line: counter,
value: firstname
});
mysublist.setSublistValue({
id: 'custpage_advs_sublist_lname',
line: counter,
value: lastname
});
mysublist.setSublistValue({
line: counter,
id: 'custpage_advs_sublist_view',
value: "<html lang='en'><body><a class='dottedlink viewitem' href='"+view_url+"'
target='blank'> View</a></body></html>"
});
counter++;
return true;
});
}
else{
return true;
}
}
else{ //POST part
var Fname= Request.parameters.custpage_advs_first_name;
var Lname=Request.parameters.custpage_advs_last_name;
var customRecord=record.create({
type:'customrecord_advs_customer_entry_form',
isDynamic:true,
});
customRecord.setValue({
fieldId:'custrecord_advs_first_name',
value:Fname
});
customRecord.setValue({
fieldId:'custrecord_advs_first_name',
value:Lname
});
var recordId=customRecord.save({
enableSourcing: false,
ignoreMandatoryFields: false
});
redirect.toSuitelet({
scriptId: 'customscript_advs_ss_editviewcolumn',
deploymentId: 'customdeploy_advs_ss_editviewcolumn',
});
}
}
return{
onRequest:onRequest
}
});
Please excuse me for a silly mistake as I have not much knowledge in scripting.
Your issue is coming from the filters part, it is not structured properly.
Saved search should be using the following structure:
search.create({
type: 'customrecord_advs_customer_entry_form',
filters: [
['custrecord_advs_first_name',"startswith",fnameValue],
// 'AND', ['another_custfield_here',"startswith",fnameValue], -- In case you wanted to add another filter
],
columns: [
search.createColumn({name: "name"}),
search.createColumn({name: "custrecord_advs_first_name"}),
....
]
});

How to update record to a custom record when the email is already exists in suitelet?

Here I am creating the Suitelet with four fields and I have created one custom record (customrecord_simple_customer_form)- internalID of my record which i have created by UI.
Then I am entering the values and submitting suitelet inputs to my custom record.
Then what iam doing is If the email is already exists in my custom record and it should be Update the records in an exising record , otherwise it has to create the new record.
/**
*#NApiVersion 2.x
*#NScriptType Suitelet
*/
define(['N/record', 'N/ui/serverWidget','N/redirect','N/runtime', 'N/log','N/http'] ,function(record, serverWidget,redirect,runtime,log,http) {
function onRequest(context) {
var Request = context.request;
var Response = context.response;
if (Request.method == 'GET') {
var form=serverWidget.createForm({title:"Sample Customer record form"});
var primaryinfo=form.addFieldGroup({
label:'Primary Information',
id:'custpage_primary_info',
});
var firstname=form.addField({
label:'First Name',
id:'custpage_first_name',
type:serverWidget.FieldType.TEXT,
container:'custpage_primary_info'
});
firstname.isMandatory=true;
var lastname=form.addField({
label:'Last Name',
id:'custpage_last_name',
type:serverWidget.FieldType.TEXT,
container:'custpage_primary_info'
});
lastname.isMandatory=true;
var email=form.addField({
label:'Email',
id:'custpage_email',
type:serverWidget.FieldType.EMAIL,
container:'custpage_primary_info'
});
email.isMandatory=true;
var phone=form.addField({
label:'Phone',
id:'custpage_phone',
type:serverWidget.FieldType.PHONE,
container:'custpage_primary_info'
});
var submit=form.addSubmitButton({
id : 'custpage_submit_customer_record',
label : 'Submit'
});
Response.writePage(form);
}
else if(Request.method == 'POST')
{
var Fname= Request.parameters.custpage_first_name;
var Lname=Request.parameters.custpage_last_name;
var Email=Request.parameters.custpage_email;
var Phone=Request.parameters.custpage_phone;
var Fullname=Fname+' '+Lname;
var customRecord=record.create({
type:'customrecord_simple_customer_form',
isDynamic:true,
});
customRecord.setValue({
fieldId:'name',
value:Fullname
});
customRecord.setValue({
fieldId:'custrecord353964',
value:Fname
});
customRecord.setValue({
fieldId:'custrecord353963',
value:Lname
});
customRecord.setValue({
fieldId:'custrecord353961',
value:Email
});
customRecord.setValue({
fieldId:'custrecord353962',
value:Phone
});
var recordId=customRecord.save({
enableSourcing: false,
ignoreMandatoryFields: false
});
redirect.toSuitelet({
scriptId: 'customscript_advs_ss_simple_ui',
deploymentId: 'customdeploy_advs_ss_simple_ui',
});
}
else{
var fieldLookUpemail = search.lookupFields({
type: search.Type.RECORD,
id: Email,
columns: ['custrecord353961']
});
var existingemail=fieldLookUpemail.email;
var customerSearchResult = search.create({
type: search.Type.RECORD,
filters: [{ name: 'custrecord353961', operator: 'is', values:existingemail }]
});
var customerInternalId = customerSearchResult[0].id;
if(existingemail==Email){
var updaterecord=record.load({
type: record.Type.RECORD,
id:customerInternalId,
isDynamic: true,
});
updaterecord.setValue({
fieldId:'name',
value:Fullname
});
updaterecord.setValue({
fieldId:'custrecord353964',
value:Fname
});
updaterecord.setValue({
fieldId:'custrecord353963',
value:Lname
});
updaterecord.setValue({
fieldId:'custrecord353962',
value:Phone
});
var updaterecordId=updaterecord.save({
enableSourcing: false,
ignoreMandatoryFields: false
});
}
}
}
return{
onRequest:onRequest
}
});

How do I generate password GUID on with suitescript 2.x

I am new to suitescript, I have been trying to generate a passwordGuid but it gives me a plain text and I expected something encrypted.
I have configured a digital ocean droplet as a SFTP client.
Generated the private and public key
I am using this code provided by one of the guys but I always don't get the expected password Guid
/**
*#NApiVersion 2.x
*#NScriptType Suitelet
*/
define([
'N/ui/serverWidget',
'N/https',
'N/log',
'N/url'
],
function (
ui,
https,
log,
url
) {
var HOST_KEY_TOOL_URL = 'https://ursuscode.com/tools/sshkeyscan.php?url=';
function getFormTemplate() {
var form;
form = ui.createForm({
title: 'Password Form'
});
form.addSubmitButton({
label: 'Submit'
});
return form;
}
function addSelectorFields(form) {
var select = form.addField({
id: 'selectaction',
type: ui.FieldType.SELECT,
label: 'Select Action'
});
select.addSelectOption({
value: 'getpasswordguid',
text: 'Get Password GUID'
});
select.addSelectOption({
value: 'gethostkey',
text: 'Get Host Key'
});
return form;
}
function addPasswordGUID1Fields(form) {
var frm = form;
frm.addField({
id: 'restricttoscriptids',
type: ui.FieldType.TEXT,
label: 'Restrict To Script Ids'
}).isMandatory = true;
frm.addField({
id: 'restricttodomains',
type: ui.FieldType.TEXT,
label: 'Restrict To Domains'
}).isMandatory = true;
return frm;
}
function addPasswordGUID2Fields(form, restrictToScriptIds, restrictToDomains) {
form.addCredentialField({
id: 'password',
label: 'Password',
restrictToScriptIds: restrictToScriptIds.replace(' ', '').split(','),
restrictToDomains: restrictToDomains.replace(' ', '').split(',')
});
return form;
}
function addHostKeyFields(form) {
form.addField({
id: 'url',
type: ui.FieldType.TEXT,
label: 'URL (Required)'
});
form.addField({
id: 'port',
type: ui.FieldType.INTEGER,
label: 'Port (Optional)'
});
form.addField({
id: 'hostkeytype',
type: ui.FieldType.TEXT,
label: 'Type (Optional)'
});
return form;
}
function onRequest(option) {
var method;
var form;
var selectAction;
var port;
var hostKeyType;
var restricttoscriptids;
var restricttodomains;
var password;
var theResponse;
var myUrl;
var url;
method = option.request.method;
form = getFormTemplate(method);
if (method === 'GET') {
form = addSelectorFields(form);
}
if (method === 'POST') {
selectAction = option.request.parameters.selectaction;
if (selectAction === 'getpasswordguid') {
form = addPasswordGUID1Fields(form);
} else if (selectAction === 'gethostkey') {
form = addHostKeyFields(form);
} else {
password = option.request.parameters.password;
log.debug("password",password)
log.debug("URL",url)
log.debug("port",port)
log.debug("hostKeyType",hostKeyType)
log.debug("restricttoscriptids",restricttoscriptids)
log.debug("restricttodomains",restricttodomains)
url = option.request.parameters.url;
port = option.request.parameters.port;
hostKeyType = option.request.parameters.hostkeytype;
restricttoscriptids = option.request.parameters.restricttoscriptids;
restricttodomains = option.request.parameters.restricttodomains;
if (restricttoscriptids && restricttodomains) {
form = addPasswordGUID2Fields(form, restricttoscriptids, restricttodomains);
}
if (password) {
form.addField({
id: 'passwordguidresponse',
type: ui.FieldType.LONGTEXT,
label: 'PasswordGUID Response',
displayType: ui.FieldDisplayType.INLINE
}).defaultValue = password;
}
if (url) {
myUrl = HOST_KEY_TOOL_URL + url + '&port=' + port + '&type=' + hostKeyType;
theResponse = https.get({ url: myUrl }).body;
form.addField({
id: 'hostkeyresponse',
type: ui.FieldType.LONGTEXT,
label: 'Host Key Response',
displayType: ui.FieldDisplayType.INLINE
}).defaultValue = theResponse;
}
}
}
option.response.writePage(form);
}
return {
onRequest: onRequest
};
});

How to filter saved 'saved search' search on type?

I am attempting to load a list of saved searches where the type is 'customer'. I can load all the searches but in order for me to determine if the saved search is a customer saved search, I need to call search.load() on each result and then check the searchType. I am running into governance issues.
I get an error (Invalid search filter) with the filter below.
How do I filter the search for customer saved searches?
require(['N/search', 'N/record'],
function GetSavedSearches(search, record) {
var records = new Array();
var typeFilter = search.createFilter({
name: 'Type',
operator: search.Operator.ANYOF,
values: 'customer'
});
var mySearch = search.create({
type: search.Type.SAVED_SEARCH,
columns: [{
name: 'internalid'
}, {
name: 'ID'
}, {
name: 'Title'
}, {
name: 'Owner'
}, {
name: 'Access'
}],
filters: typeFilter
});
mySearch.run().each(processRecord);
function processRecord(result) {
var columns = result.columns();
var searchID = result.getValue({
name: 'ID'
});
try {
var loadedSearch = search.load({
id: searchID
});
var searchName = result.getValue({
name: 'Title'
});
var searchType = loadedSearch.searchType;
var searchAccess = loadedSearch.isPublic;
if (searchType == "customer") {
var record = {
SS_ID: result.id,
'Title': searchName,
'Type': searchType,
'Public': searchAccess
};
records.push(record);
}
}
catch (ex) {
// an error occurs when trying to load a search that is actually an update.
}
var x = 0;
return true;
}
});
You have to define the filter as this:
var typeFilter = search.createFilter({
name: 'recordtype',
operator: search.Operator.ANYOF,
values: 'Customer'
});

Populate with inherited document in Mongoose

I am trying to create a database schema for the following model:
I am not sure what the better way to represent this in a MongoDb would be, but since I am using Mongoose and there is a plugin for inheritance, I am trying the following:
var mongoose = require('mongoose')
, extend = require('mongoose-schema-extend')
, Schema = mongoose.Schema
, ObjectId = mongoose.Schema.Types.ObjectId
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function callback () {
//Mashup and Item are bound (itemSchema is a sub-doc)
var itemSchema = new Schema({
pos: { top: Number, left: Number }
, size: { width: Number, height: Number }
, component: { type: ObjectId, ref: 'Component' }
})
var mashupSchema = new Schema({
name: String
, desc: String
, size: { width: Number, height: Number }
, items: [itemSchema]
})
var componentSchema = new Schema({
name: String
, desc: String
}, { discriminatorKey : '_type' })
var imageComponentSchema = componentSchema.extend({
url: String
})
var textComponentSchema = componentSchema.extend({
text: String
})
var htmlComponentSchema = componentSchema.extend({
html: String
})
var webComponentSchema = componentSchema.extend({
page: { type: ObjectId, ref: 'Page' }
, selector: { type: ObjectId, ref: 'Selector' }
})
var pageSchema = new Schema({
name: String
, desc: String
, url: String
, active: { type: Boolean, default: false }
, webComponents: [{ type: ObjectId, ref: 'WebComponent' }]
})
var selectorSchema = new Schema({
desc: String
, url: String
, cssPath: String
})
///MODELS
var Mashup = db.model("Mashup", mashupSchema)
var Component = db.model("Component", componentSchema)
var ImageComponent = db.model("ImageComponent", imageComponentSchema)
var TextComponent = db.model("TextComponent", textComponentSchema)
var HtmlComponent = db.model("HtmlComponent", htmlComponentSchema)
var WebComponent = db.model("WebComponent", webComponentSchema)
var Page = db.model("Page", pageSchema)
var Selector = db.model("Selector", selectorSchema)
//CREATE
//a new empty mashup
//var aMashup = new Mashup({ name: "Test" });
Mashup.create({ name: "Test" }, function (err, mashup) {
if (err) return
console.log("Saved: empty mashup")
//mashup saved, create a webComponent
var aWebComponent = new WebComponent({ name: "Map", desc: "A map" })
//create a page
var aPage = new Page({ name: "Maps", desc: "Google Maps", url: "http://maps.google.com" })
aPage.webComponents.push(aWebComponent)
aWebComponent.page = aPage
//create a selector
var aSelector = new Selector({desc: "Just the map", url: "maps.google.com", cssPath: "#map" })
aWebComponent.selector = aSelector
//save the component
aWebComponent.save(function(err) {
if (err) return
console.log("Saved: WebComponent")
aPage.save(function(err) {
if (err) return
console.log("Saved: the Page")
aSelector.save(function(err) {
if (err) return
console.log("Saved: the Selector")
//finally add the item with the new component
var item = { pos: { top:6, left:10 }, size: { width:100, height:100}, component: aWebComponent }
mashup.items.push(item)
mashup.save(function (err) {
if (err) return
console.log("Saved: mashup with item (WebComponent with Page and Selector)")
//POPULATE
Mashup
.find({})
.populate("items.component")
.exec(function (err, mashup) {
if (err) console.log(err)
console.log(mashup);
})
})
})
})
})
})
});
This is a use case scenario, where a user creates a Mashup and then adds a new Item to it by creating a new WebComponent. I need that Item class because each different mashup should be able to have "instances" (i.e. the Items) of existing Components.
Now, I am new to Mongoose and I am sure things could be done differently. Any suggestion here is welcome. However, when I try to query the Mashups populating the results, the output I get is:
Saved: empty mashup
Saved: WebComponent
Saved: the Page
Saved: the Selector
Saved: mashup with item (WebComponent with Page and Selector)
[ { __v: 1,
_id: 520a8aae3c1052f723000002,
name: 'Test',
items:
[ { component: null,
_id: 520a8aaf3c1052f723000006,
size: [Object],
pos: [Object] } ],
size: {} } ]
component should be populated but it is not. I guess this is because it expects a Componentwhile it gets a WebComponent. How do I fix this? Should I stop trying with inheritance? What other ways are there to create a DB schema for this model?
Doh.. changing
var componentSchema = new Schema({
name: String
, desc: String
}, { discriminatorKey : '_type' })
to
var componentSchema = new Schema({
name: String
, desc: String
}, { collection : 'components', discriminatorKey : '_type' })
Fixes the issue. Not sure why.

Resources