Push document into sub document in array of mongoose model - arrays

in my company schema i have a posted job which is type array and will hold subdocuments
companySchema.js
PostedJobs : [{
JobName : { type: String, required : true},
JobType : { type: String, required : true},
JobLocation : { type: String, required : true},
JobSalay: { type: String, required : true}
}],
in my /company route i get all company registered by specific user through Creatorentity in model
to get that user company i use
router.get('/', isLoggedIn , function(req, res, next) {
Company.find({'Creator': req.user.id}).then(function(companies) {
res.render('Company', { "Companies" : companies });
});
});
after getting company i want to visit a specific company page on clicking company name(unique)
router.get('/:name' , isLoggedIn , function(req , res , next) {
var name = req.params.name;
Company.findOne({Name : name}).then(function(Company) {
res.render('dashboard',{
"Company" : Company,
errors : []
});
})
});
now i want to post a job to this specific company from a POST route as
my req.body consist of JobName , JobType , JobLocation and JobSalary which i have assigned to a specific variable now how should i push this doc to array
POST route
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;
//push this job to that specific comapny
});

I don't know the schema of your company, but if you want to add PostedJobs to the companies, you should define an array field in it.
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;
//push this job to that specific comapny
// create the postedJob object
var postedJob = {JobName : JobName, JobType : JobType, JobLocation : JobLocation, JobSalay:Salary};
// find the company in DB and add the postedJob to its array of postedJobs
var name = req.params.name;
Company.findOne({Name : name}).then(function(company) {
//modify and save the object received via callback
company.postedJobs.push(postedJob);
company.save();
});
});

Related

PUSH id in order like add to cart

I created model schema for users and products with simple CRUD, my next project is my model schema order where I push my userId and projectId in the array in order.
this is the code that I created in the controller
module.exports.makeOrders = (reqBody) => {
let newOrder = new Order({
totalAmount : reqBody.totalAmount,
usersOrder.push({
userId : reqBody.userId,
project : reqBody.projectId
}),
})
return newOrder.save().then((order, error) =>{
if(error){
return false;
}
else{
return true;
}
})
}
and this is my route
router.post("/checkout", (req, res) => {
let data = {
userId : req.body.userId,
productId : req.body.productId
}
userController.makeOrders(data).then(resultFromController => res.send(resultFromController))
})
this is my model
const orderSchema = new mongoose.Schema({
totalAmount : {
type : Number,
required : true
},
purchasedOn : {
type : Date,
default : new Date
},
usersOrder :[
{
userId : {
type : String,
required : true
},
productId : {
type : String,
required : true
},
}
]
})
this is what I enter in postman
{
"totalAmount" : 1000,
"userId" : "62a9c46c4d15dc8157c375aa",
"productId" : "62aafe01d9337ce87ff5aaa1"
}
the error that I'm experiencing is "SyntaxError: Unexpected token '.' "
based on what I know I put the push method in the wrong place. I just copy the create method in the user which is working. I don't know why it is not working in order controller.
Note. I just started to learn json.
You have to update your routes like this as you are missing the totalAmount field and inside your schema you mentioned it as required fields.
router.post("/checkout", (req, res) => {
let data = {
userId : req.body.userId,
productId : req.body.productId,
totalAmount: req.body.totalAmount
}
userController.makeOrders(data).then(resultFromController => res.send(resultFromController))
})

Unable to query using the dynamic id field in function(req, res, next, id) mongoose ( mongodb )

I'm using mean js, I'm trying to query mongodb via a Service call in angularjs,
var Priority = 'Left_VM_P';
url = currentUrl+"/api/queryPrioritySearch/"+Priority;
the query works only when
Property.find({ Left_VM_P : true }).exec(function(err, properties) {
when i try to replace the variable Left_VM_P with the value of the id, it doesn't respond.
exports.queryPrioritySearch = function(req, res, next, id) {
console.log('id = ', id);
Property.find({ id : true }).exec(function(err, properties) {
Upon console logging
the value of id comes to be
id = Left_VM_P
Here's the sample mongo object.
{
"Left_VM_P": true,
"Later_P": true,
"High_P": true,
"last_date_call_was_made": "-",
"call_priority": "-"
}
Also when I search in the mongo shell it returns value correctly.
> db.properties.find({"Left_VM_P" : true}).count();
3
i think you can not put variable on left side of mongodb query. mongodb always consider left side as field name as string. so
Property.find({ Left_VM_P : true }).exec(function(err, properties)
will work because it consider left_VM_P as string so it is like "Left_VM_P": true
in case of Property.find({ id : true }) it is taking it as string "id":true
but you want dynamic name in place of id so you can try this solution
var dynamicId={};
dynamicId[id]=true;
Property.find(dynamicId).exec(function(err, properties)
i hope this will help :)
Here's the full version:
exports.queryPrioritySearch = function(req, res, next, id) {
var id_2 = id;
var dynamicId={};
dynamicId[id_2]=true;
Property.find(dynamicId).exec(function(err, properties) {

how to query mongoose with multiple query params via an object or an array?

I want to send js object to the backend or an array so that in the backend code ( below ) I can use the values and make a search in the mongodb ( using mongoose ) to get the data.
server code
exports.prioritySearch = function(req, res, next, id) {
console.log( 'prioritySearch-API id = ', id);
console.log( ' req.params = ', req.params);
// console.log( ' req = ', req);
// Property.find({ Left_VM_P : 'true' }).exec(function(err, properties) {
Property.find({ id : 'true' }).exec(function(err, properties) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.jsonp(properties);
}
});
};
Angular Service that calls this api
.factory('prioritySearchSvc', function($q, _, $http, currentUrl, TodayDateSvc) {
console.log('186-S---- inside SinglePropertyDataService ');
var Priority = 'Left_VM_P';
var deferred = $q.defer(),
url = currentUrl+"/api/prioritySearch/"+Priority;
This below code works but next one don't which I dont understand why.
// below query works
Property.find({ Left_VM_P : 'true' }).exec(function(err, properties) {
// but i want below query to work coz i want to change the id parameter so I can modify each time what key is searched for, here id = Left_VM_P but why isn't it working..
Property.find({id : 'true' }).exec(function(err, properties) {

how to make primary key / _id optional to input in mongoose

I want make primary key no need to input but primary key auto generate in mongodb.
so, i use {type : ObjectId,required:false}, but it wont work because I let the primary key empty. so is there another ways to make pprimary key optional to input? Thankyou
rest api model
var mongoose = require("mongoose");
var Schema = mongoose.Schema;
var ObjectId = Schema.ObjectId
var accessmenu = new Schema({
_id : {type : ObjectId,required: false},
acc_id : String,
name : String,
read : Boolean,
execute : Boolean
},{ collection: 'access_menu'});
var accessmenu = mongoose.model("accessmenu",accessmenu);
module.exports.accessmenu = accessmenu;
rest api
app.put("/access_menu/:id",function(req,res){
var AccessMenu = new accessmenu({
_id : req.body._id,
acc_id : req.body.acc_id,
name : req.body.name,
read : req.body.read,
execute : req.body.execute
});
AccessMenu.save(function(err){
if(err)
{
accessmenu.update({_id : req.params.id},{$set:{acc_id : req.body.acc_id,
name : req.body.name,
read : req.body.read,
execute : req.body.execute
}},function(err,users){
if(err)
{
data['error'] = 1;
data['Access_Menu'] = "update faill";
res.json(data);
}
else
{
data['error'] = 0;
data['Access_Menu'] = "update success";
res.json(data);
}
});
}
else
{
data['error'] = 0;
data['Access_Menu'] = "input success";
res.json(data);
}
});
});
script.js
if($scope.data_acc_lv.length > 0)
{
for(var i = 0;i<$scope.data_acc_lv.length;i++)
{
var input3 = {
"_id" : $scope.data_acc_lv[i]._id,
"acc_id":$scope.accLvID,
"name": $scope.data_acc_lv[i].name,
"read": $scope.data_acc_lv[i].read,
"execute": $scope.data_acc_lv[i].execute
}
$http.put("http://localhost:22345/access_menu/" + $scope.data_acc_lv[i]._id,input3)
.success(function(res,err){
if(res.error == 0)
{
$scope.data_acc_lv.length = 0;
}
else
{
console.log(err);
}
});
}
}
Mongoose assigns each of your schemas an _id field by default if one is not passed into the Schema constructor. The type assigned is an ObjectId to coincide with MongoDB's default behavior.
If you don't want an _id added to your child schema at all, you may disable it using this option.
// disabled _id
var childSchema = new Schema({ name: String }, { _id: false });
var parentSchema = new Schema({ children: [childSchema] });
You can only use this option on sub-documents. Mongoose can't save a document without knowing its id, so you will get an error if you try to save a document without an _id.
http://mongoosejs.com/docs/guide.html

Saving multiple field array in mongodb using mongoose

//Here is model
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var ObjectId = Schema.ObjectId;
// Task schema
var taskSchema = mongoose.Schema({
tasktype : {type: String},
createdon : {type: Date, default: Date.now},
createdby : {type: Schema.Types.ObjectId,ref: 'User'},
visitedby : [{type: Schema.Types.ObjectId,ref: 'User'}],
taskinfo : [{ isactive:Boolean, taskobject:String, taskdetails:String, iscompleted:Boolean}]
});
module.exports = mongoose.model('Task', taskSchema);
// route
var Task = require ('../models/task');
var User = require ('../models/user');
var config = require ('../../config');
module.exports = function(app, express) {
var api = express.Router();
api.post('/tasks', function (req, res) {
var task = new Task({
// ...
tasktype : req.body.tasktype,
taskinfo : req.body.taskinfo,
});
task.save(function(err){
if(err){
res.send(err);
return;
}
res.json({message:'Task has been created'})
});
return api
}
While all other fields getting saved but the one with array with multiple fields always return blank like "taskinfo : [ ] "
The post method is REST API to post a task into mongoose database, for array with single field everything working fine but array with multiple field is not getting saved, someone please help me here.
Basic help will be fine, just please teach me how to save "multiple field array".
Mongoose doesnot always require subdocument structure and this can be achieved by the above model, please dont advice to use subdocument structure, I want to learn this.
Thank You.
I think if taskinfo has a multiple values and you want to save it as embedded document inside task document. You should have different document of task info. So,you can save like that
var TaskInfoSchema = require("taskInfo.js").TaskInfoSchema
var taskSchema = mongoose.Schema({
tasktype : {type: String},
createdon : {type: Date, default: Date.now},
createdby : {type: Schema.Types.ObjectId,ref: 'User'},
visitedby : [{type: Schema.Types.ObjectId,ref: 'User'}],
taskinfo : [TaskInfoSchema]
});
module.exports = mongoose.model('Task', taskSchema);
And now you will have different document as task info like
var taskInfo = mongoose.Schema({
isactive:{type:Boolean},
taskobject:{type:String},
taskdetails:{type:String},
iscompleted:{type:Boolean}
});
var TaskInfo = mongoose.model('TaskInfo', taskSchema);
module.exports.TaskInfo = TaskInfo
module.exports.TaskInfoSchema = taskSchema
When you will save task document,
Var TaskInfo = new TaskInfo({
isactive:true,
taskobject:"",
taskdetails:"",
iscompleted:true
})
var task = {};
task.tasktype = req.body.tasktype;
you can push it
task.taskinfo = [];
for (var i = 0; i < req.body.taskInfo.length; i++) {
var taskInfo = new TaskInfo(req.body.taskInfo[i]);
task.taskinfo.push(taskInfo);
}
Then you will save task document
var taskObj = new Task(task);
taskObj.save(function (err) {
if (err) {
res.send(err);
return;
}
res.json({
message: 'Task has been created'
})
});
});

Resources