Push data to an embedded array using mongoose - node.js

My Schema look like this
var Company ={
Name
Email
Location
Industry
Creator
PostedJobs : [{
JobName
JobType
JobLocation
JobSalary
Applicants : [{
Name
Status
}]
}]
}
to push job here is my route code which is working
router.post('/:name' , isLoggedIn , function(req , res , next) {
var JobName = req.body.JobName;
var JobType = req.body.JobType;
var JobLocation = req.body.JobLocation;
var Salary = req.body.Salary;
var postedJob = {JobName : JobName, JobType : JobType, JobLocation : JobLocation, JobSalary:Salary};
var name = req.params.name;
Company.findOne({Name : name}).then(function(Company) {
Company.PostedJobs.push(postedJob);
Company.save();
req.flash('sucess_msg' , 'Job Added Sucessfully');
res.render('dashboard',{
"Company" : Company
});
});
});
now i want to push applicants on apply button
apply code is
router.get('/:id/apply' , isLoggedIn , function(req , res , next) {
var appicant = { Name : req.user.FirstName,
Status : "Applied"
};
Company.find({'PostedJobs._id' : req.params.id}).then(function(job) {
Company.PostedJobs.Applicants.push(applicant);
Company.save();
req.flash('sucess_msg' , 'Job Added Sucessfully');
res.redirect('/jobs');
});
});
i also tried
which is not working and i wont know what to do with this

Can you try this? when pushing applicants.
Company.PostedJobs[0].Applicants.push(applicant);

Related

Not able to find the right Document

I am a working on a project for my school. I want to delete employees in the database. This can be done by setting the attribute isDeleted to true.
isDeleted : {
type : Boolean,
default :false,
required : true
}
and the controller function:
const deleteEmployee = async(req, res)=>{
try{
const employeeID = req.body.id;
console.log(employeeID);
const employee = await Member.findByIdAndUpdate(employeeID, {isDeleted : true}, {new : true});
res.status(200).json(employee)
}catch(err){
console.log(err);
}
}
I am not able to update the database. Please suggest changes.

NetSuite SuiteTalk 2.0 address sublist defaultshipping and defaultbilling not being set

I am having a heck of a time getting the defaultshipping and defaultbilling checks to be set when inserting a new customer record. I have included my code below and have tried several different things but for some reason on the first address that is inserted both defaultshipping and defaultbilling are set but the second address has nothing checked.
define([ 'N/record', 'N/runtime' ],
function(record, runtime) {
function doPost(requestBody) {
var custRec = record.create({
type : record.Type.CUSTOMER,
isDynamic : true
});
var addresses = [
custBillAddr = {
addr1 : '2100 S. Blah St.',
addr2 : '',
addressee : 'Test Person',
city : 'Test Ville',
defaultbilling : true,
defaultshipping : false,
state : 'IA',
zip : '12345'
}, custShipAddr = {
addr1 : '5144 S. Test St.',
addr2 : '',
addressee : 'Tester Test',
city : 'Test City',
defaultbilling : false,
defaultshipping : true,
state : 'TX',
zip : '54321'
}];
var curScript = runtime.getCurrentScript();
var defEntity = curScript.getParameter({
name : 'custscript_default_entity_status'
});
var defSub = curScript.getParameter({
name : 'custscript_default_subsidary'
});
var custData = {
accountnumber : '112233',
companyname : 'Testing Company',
email : 'Testing#example.com',
entityid : '112233',
entitystatus : defEntity,
externalid : '123',
subsidiary : defSub,
};
for ( var key in custData) {
if (custData.hasOwnProperty(key)) {
custRec.setValue({
fieldId : key,
value : custData[key]
});
}
}
/* create address sub lists here */
custRec = upsertAddresses(custRec, addresses);
var recordId = custRec.save({
enableSourcing : false,
ignoreMandatoryFields : false
});
return JSON.stringify(recordId);
}
function upsertAddresses(custRec, addresses) {
for ( var address in addresses) {
custRec.selectNewLine({ sublistId : 'addressbook' });
var addList = custRec.getCurrentSublistSubrecord({ sublistId : 'addressbook', fieldId : 'addressbookaddress' });
for ( var key in addresses[address]) {
addList.setValue({ fieldId : key, value : addresses[address][key] });
}
custRec.commitLine({ sublistId : 'addressbook' });
}
return custRec;
}
return {
post : doPost,
};
});
In the addresses array of address objects I tried using:
defaultbilling : true
defaultbilling : 'T'
defaultbilling : 'Yes'
defaultbilling : 1
but none of them worked to set the field and I am not getting an error. Hoping someone here can tell me what I did wrong when trying to set those fields.
I had a very similar issue. Turns out that the addressbook in 2.0 needs a subrecord of the sublist. The code below is not exactly what you are asking for, but it should help you with what you need to do. In mine I'm getting the values, where you just need to set them. Hope this helps out.
define(['N/record','N/https','N/search'],function(record,https,search){
function sendContactData(context){
var contactNewRecord=context.newRecord;
if(context.type=='create' || contactNewRecord.getValue('nluser')=='1234'){return;}
var contactID=contactNewRecord.getValue('id');
var contactObjectRecord=record.load({type:record.Type.CONTACT,id:contactID,isDynamic:true,});
var shippingAddr1='';
var shippingCity='';
var shippingState='';
var shippingZip='';
var shippingCountry='';
var numLines=contactNewRecord.getLineCount({sublistId:'addressbook'});
if(numLines>0){
for(var addressCount=0;addressCount<numLines;addressCount++){
var addressShipping=contactNewRecord.getSublistValue({
sublistId:'addressbook',
fieldId:'defaultshipping',
line:addressCount
});
if(addressShipping==true){break;}
}
}
if(addressShipping==true){
//Select the line set as the default shipping:
contactObjectRecord.selectLine({sublistId:"addressbook",line:addressCount});
var shippingAddressSubrecord=contactObjectRecord.getCurrentSublistSubrecord({sublistId:"addressbook",fieldId:"addressbookaddress"}); //Access the addressbookaddress subrecord:
if(shippingAddressSubrecord){
shippingAddr1=shippingAddressSubrecord.getValue({fieldId:'addr1'});
shippingCity=shippingAddressSubrecord.getValue({fieldId:'city'});
shippingState=shippingAddressSubrecord.getValue({fieldId:'state'});
shippingZip=shippingAddressSubrecord.getValue({fieldId:'zip'});
shippingCountry=shippingAddressSubrecord.getValue({fieldId:'country'});
}
}
}; /* END sendContactData() */
return{
afterSubmit:sendContactData
} /* END return block */
}); /* END define(['N/record'],function(record) */

Connecting Node.js to MongoDB using monk

I am trying to store the data written in jade to be stored in MongoDB using monk, but it is neither storing the data nor prompting any error
connecting to MongoDB code: (p1 is the name of the database)
var mongo = require('mongodb');
var monk = require('monk');
var db = monk('localhost:27017/p1');
index.js code to store in DB:
/* GET New User page. */
router.get('/addnew', function(req, res) {
res.render('addnew', { title: 'Add New Theatre' });
});
/* POST to Add User Service */
router.post('/addnew', function(req, res) {
// Set our internal DB variable
var db = req.db;
// Get our form values. These rely on the "name" attributes
var theatrename = req.body.TheatreName;
var screen = req.body.Screen;
var latitude = req.body.Latitude;
var longitude = req.body.Longitude;
var city = req.body.City;
// Set our collection (Theatre is the name of the collection)
var collection = db.get('Theatre');
// Submit to the DB
collection.insert({
"TheatreName" : theatrename,
"Screen" : screen,
"Latitude" : latitude,
"Longitude" : longitude,
"City" : city,
}, function (err, doc) {
if (err) {
// If it failed, return error
res.send("Not adding into db.");
}
else {
// And forward to success page
res.send("Theatrelist");
}
});
});
module.exports = router;
This is my jade code:
extends layout
block content
h1= title
form#formAddUser(name="adduser",method="post",action="/adduser")
p Thearte Name:
input#inputName(type="text", name="ThearteName")
br
p Screen :
input#inputScreen(type="text", name="Screen")
br
p Latitude:
input#inputUserLat(type="text", name="Latitude")
br
p Longitude:
input#inputlong(type="text", name="Longitude")
br
p City:
input#inputCity(type="text", name="City")
br
br
button#btnSubmit(type="submit") submit
If I were you I will try to do this:
show in console that vars from "req.body.VAR" are send correctly.
For example
router.post('/addnew', function(req, res) {
console.log(req.body.Screen);
Then, I will try to add some data to the BD for example:
collection.insert({
"TheatreName" : "Fakename",
"Screen" : "Fakescreen",
"Latitude" : "0",
"Longitude" : "0",
"City" : "Fakecity",
}, function (err, doc) {
if (err) {
// If it failed, return error
res.send("Not adding into db.");
}
else {
// And forward to success page
res.send("Theatrelist");
}
});
If you can see the result in your BD, all is OK (else, is in connection or something similar).
I hope my answer will help you!

NodeJS / Express 4 - Sqlite3 - Storing rowset into variable

I'm trying to store the rowset from the query below into a variable so I can play it into the view and loop through it.
I'm getting results from the DB, and can console.log them in the db.each block, and I thought I could generate my JSON object below and then store it - but it's not setting it for some reason and var data = "" just returns an empty string.
I am a bit baffled as to why - does anyone know where I am going wrong please?
Thank you for taking the time to read.
var express = require('express');
var router = express.Router();
var db = require('../lib/db.js');
/* GET contacts listing. */
router.get('/', function(req, res) {
var data = "";
db.serialize(function() {
var rowset = db.each("SELECT b.forename, b.surname FROM contacts a, contact_attributes b WHERE a.contact_id = b.contact_id", function(err, row) {
data = ' { "'+row.contact_id+'" : [ { "forename" : "'+row.forename+'", "surname" : "'+row.surname+'" } ] } ';
});
});
res.render('contacts', {
title: "Contacts",
active: "contacts",
contacts: JSON.stringify(data)
});
});
module.exports = router;
The database query runs asynchronously, executing the callback function once the query returns. Therefore, res.render is called after data gets set to empty string, but before it gets set to the result set.
Also, there is no need to JSON.stringify a string that you have already built as JSON.
The code executes as follows:
var data = "";
db.serialize
var rowset = db.each
res.render
DB query returns.
db.each callback function executes, which sets data based on the result set.
Try this:
db.serialize(function() {
var rowset = db.each("SELECT forename, surname FROM contacts a, contact_attributes b WHERE a.contact_id = b.contact_id", function(err, row) {
var data = ' { "'+row.contact_id+'" : [ { "forename" : "'+row.forename+'", "surname" : "'+row.surname+'" } ] } ';
res.render('contacts', {
title: "Contacts",
active: "contacts",
contacts: data
});
});
});
});
or, avoid the manual JSON stringification:
db.serialize(function() {
var rowset = db.each("SELECT forename, surname FROM contacts a, contact_attributes b WHERE a.contact_id = b.contact_id", function(err, row) {
var data = {};
data[row.contact_id] = [
{
forename: row.forname,
surname: row.surname
}
];
res.render('contacts', {
title: "Contacts",
active: "contacts",
contacts: data
});
});
});
});

after saving in mongoose {strict : false},can't edit after findOne()

this is my schema
name : String,
phone : String,
address : String
mongoose.model("user",userSchema);
var user = mongoose.model("user");
var newUser = new user({name : "d",phone : "p",address : "q"});
newUser.save();
newUser.findOne({_id : "dsklfj98908"},function(err,result){
result.set('unlockGames',"puzzle",[String],{strict : false});
result.save();
});
working wonderful,until i want to change one more time:
//NOT WORKING 1
newUser.findOne({_id : "dsklfj98908"},function(err,result){
result.get("unlockGames").push("Gag jan stees");
result.save();
});
//NOT WORKING 2
newUser.findOne({_id : "dsklfj98908"},function(err,result){
var unlockGames = result.get("unlockGames").push("Gag jan stees");
result.set('unlockGames',unlockGames,[String],{strict : false});
result.save();
});
Help please!)
now it's working
var game = "es chlnei duq inch eiq anelu";
var unlockGames = result.get("unlockGames");
result.unlockGames = unlockGames.push(game);
result.markModified('unlockGames');
that's it);

Resources