How to get and set function using inside mongoose schema - node.js

How to use if condition inside schema creation,
my schema is,
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var testSchema = new Schema({
"Name":String,
"TestValue":String
}, {
collection: 'test'
});
testSchema.eachPath(function(path) {
console.log(path);
});
testSchema.path('TestValue').set(function(value) {
console.log("value: " + value);
value="FFF";
this.TestValue = value;
return value;
});
module.exports = mongoose.model('test', testSchema);
I have to change TestValue based on the if condition,how to solve the problem...pls give me some solution to solve that problem.

You have a few options here. Here are a couple:
testSchema.path('TestValue').set(function(value) {
if (value === 'uh oh') {
return 'a different value';
} else {
return value;
}
});
Or you can use a ternary if you're so inclined:
testSchema.path('TestValue').set(function(value) {
return (value === 'uh oh') ? 'a different value' : value
});

Related

getting empty array in mongoose by using mongoDB

var mongoose = require("mongoose")
var mongooseSchema = new mongoose.Schema({
empId: Number,
empName: String,
empId: Number
});
var Model = mongoose.model("employee", mongooseSchema);
mongoose.connect("mongodb://localhost/company");
Model.find(employeeDetails)
function employeeDetails(error, data) {
if (error == null) {
console.log(data);
} else {
console.log(error)
}
mongoose.disconnect();
}
var Model = mongoose.model("Model", mongooseSchema, "Employees");

Cannot access mongoose schema attribute

So... I basically search an item in the database, find it, print it fine but I can t access the attributes. When I try to print them they show undefined.
I know that the attribute are in fact undefined because it doesn t break the loop and I do have both attributes in my mongoose schema. I also tried to stringify and parse it to json back and didn t work. (this is all the material I could find)
This is the script:
const name_to_find = 'Copac';
async function myFetch(){
const express = require('express');
const mongoose = require('mongoose');
const Item = require('./models/Item');
const mongoUrl = process.env.MONGO_URL;
const appsc = express();
var connectWithRetry = function() {
return mongoose.connect(mongoUrl, { useNewUrlParser: true, useUnifiedTopology: true }, function(err) {
if (err) {
console.error('Failed to connect to mongo on startup - retrying in 3 sec', err);
setTimeout(connectWithRetry, 3000);
}
});
};
connectWithRetry();
var date1 = new Date();
while(true){
var date2 = new Date();
if(date1.getTime() - date2.getTime() > 100000)
break;
try {
const response = await Item.find({name: name_to_find});
var mergi = JSON.parse(JSON.stringify(response));// doesn t work
//if (response['status'] == 1)
if(response.status == 1){
console.log("200");
break;
}
else {
console.log(JSON.stringify(response));
console.log(response.status);
console.log(mergi.name);
}
}
catch (err) {
console.error(err);
console.log(name_to_find);
}
}
}
myFetch();
this is the schema:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const ItemSchema = new Schema({
status: {
type: Number,
required: true
},
name: {
type: String,
required: true
}
});
module.exports = Item = mongoose.model('item', ItemSchema);
and this is the output:
[{"_id":"60fc235414d05a001a5fa630","status":1,"name":"Copac","__v":0}]
undefined undefined
As u see, it is indeed 1 and should exit the loop but it doesn t.
nothing here helped either link.
Ok so the problem was that mongoose treats the result of .find() function as an array and I should have casted it with results[0] or use .findOne(). I chose the former. The answer was actually in the link provided but u have to scroll a bit for it. Tell me if u want me to delete this

Mongoose: Saving ref of another document into an array of objects document returns empty array

I'm trying to add specific document's ref id into another document's array of object. So that I can use populate method. But somehow the array remains empty even after pushing the ref.
Please help me. Thank you in advance.
Here is list.js:
const mongoose = require('mongoose');
const User = require('./user');
const Task = require('./task');
const Schema = mongoose.Schema;
// User Schema
const ListSchema = mongoose.Schema({
item:{
type: String,
required: true
},
purpose:{
type: String,
required: true
},
user: {
type: Schema.ObjectId,
ref:"User"
},
deadline:{
type: Date,
default: null
}
});
const List = module.exports = mongoose.model('List', ListSchema);
task.js:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const List = require('./list');
// User Schema
const TaskSchema = mongoose.Schema({
task:{
type: String,
required: true
},
list: [{
type: Schema.Types.ObjectId,
ref:'List'
}]
});
const Task = module.exports = mongoose.model('Task', TaskSchema);
Here is how I create and save new task instance:
const express = require('express');
const mongoose = require('mongoose');
const router = express.Router();
let List = require('../models/list');
let User = require('../models/user');
let Task = require('../models/task');
router.post('/add', isAuthenticated, function(req,res){
var tasker = req.body.task, listshash= [];
var startIndex = 0, index;
var x,y,listid= [];
while ((index = tasker.indexOf("#", startIndex)) > -1) {
var ind = tasker.indexOf(" ", index);
if(ind == -1)
listshash.push(tasker.substring(index+1));
else
listshash.push(tasker.substring(index+1,ind));
startIndex = index + 1;
}
//Instance of task
var taskIns = new Task({task: req.body.task});
List.find({user: req.session.passport.user}, function(err, lists){
for(x in lists){
for(y in listshash){
if(lists[x].item.toLowerCase().replace(/\s/g,'') == listshash[y]){
//lists[x] contains the document "list" that I want to store as
//ref in list property array of task
taskIns.list.push(lists[x]);
//console.log(taskIns.list.push(lists[x]));
}
}
}
});
taskIns.save(function(err, doc){
if(err) res.json(err);
else {
console.log("Saved");
res.redirect('/lists');
}
});
});
module.exports = router;
This is how the database collection of tasks look like after inserting data:
See the data
You should have to use async npm
List.find({user: req.session.passport.user}, function(err, lists){
async.each(lists ,function(x,callback){
async.each(listhash, function(y,callback){
if(x.item.toLowerCase().replace(/\s/g,'') == y){
taskIns.list.push(x);
}
});
});
//After that you can do save the data
taskIns.save(function(err, doc){
if(err) res.json(err);
else {
console.log("Saved");
res.redirect('/lists');
}
});
});
It's not saving the refs because you are dealing with asynchronous functions; you are pushing the lists within the find() callback and the taskIns model save event happens before the push.
You can move the taskIns save operation within the find() callback or use promises to tackle the issue.
For example, using callbacks:
List.find({ user: req.session.passport.user}, (err, lists) => {
const taskIns = new Task({task: req.body.task});
for(x in lists) {
for(y in listshash) {
if(lists[x].item.toLowerCase().replace(/\s/g,'') == listshash[y]) {
taskIns.list.push(lists[x]);
}
}
}
taskIns.save((err, doc) => {
if(err) res.json(err);
else {
console.log("Saved");
res.redirect('/lists');
}
});
});

populate query does not show newly added referenced item

My schema is as follows:
items.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var ItemSchema = new Schema({
no_of_times_ordered:Number,
item_name:String,
item_tag:String,
item_category:String,
item_illustrations:[String],
item_stock:Number, //0 available 1 last 5 items 2 not available
item_quantity_ordered:{type:Number,default:0},
item_discount_price:Number,
item_price:Number,
item_img:String,
no_of_likes:{type:Number,default:0}
},{ versionKey: false });
module.exports = mongoose.model('items',ItemSchema);
foodtruck.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var Items = require('./items.js');
var FoodTruckSchema = new Schema({
foodtruck_name:String,
foodtruck_location:String,
foodtruck_rating:{type:Number,default:5},
foodtruck_total_votes:{type:Number,default:0},
foodtruck_tag:String,
foodtruck_open_status:{type:Number,default:1}, //0 open 1 closed
foodtruck_starting_timing:String,
foodtruck_closing_timing:String,
foodtruck_cusine:String,
foodtruck_img:String,
foodtruck_logo:String,
item_list: [ {type : mongoose.Schema.ObjectId, ref : 'items'}]
},{ versionKey: false });
module.exports = mongoose.model('foodtruck',FoodTruckSchema);
My query is as below:
var addItem = function(req, res) {
var foodtruck_id = req.body.foodtruck_id;
var newItem = new item();
var itemList = [];
newItem.item_name = req.body.item_name;
newItem.item_tag = req.body.item_tag;
newItem.item_category = req.body.item_category;
for (var key in req.body) {
if (req.body.hasOwnProperty(key)) {
if (key == 'item_illustrations') {
newItem.item_illustrations = req.body[key];
}
}
}
newItem.item_stock = req.body.item_status;
newItem.item_price = req.body.item_price;
if ((foodtruck_id) && (foodtruck_id.trim() != '')) {
foodtruck.findById(foodtruck_id.trim(), function(err, foodtrucks) {
if (err)
res.json({
status: '500',
message: 'There is no data available'
});
newItem.save(function(err, savedItem) {
if (!err) {
foodtrucks.item_list.push(savedItem._id);
foodtrucks.save();
foodtruck.find({
_id: foodtruck_id.trim()
}).populate('item_list').exec(function(err, foodtrucks) {
res.json({
status: '200',
message: 'New item added successfully',
data: foodtrucks
});
});
} else {
res.json({
status: '500',
message: 'Error while saving new item'
});
}
});
});
}
}
The main problem I am facing is that, I am able to create new item ,add its reference to the foodtruck schema, but somehow when I put populate query for the same foodtruck, the newly created item does not show. So,can you tell me how exactly I can show this item via populate query?
I think you got to put the populate inside the save function to make the populate method happen after the save.
foodtrucks.save(function(err, doc) {
//do population here
});
using asynchronous methods.

NodeJS - .save() is not a function. Unable to create collection via mongoose

I am also facing .save() is not a function error, but I have gone through most of the similar SO Questions and tried their respective answers but to vain. But through my terminal, I am being able to create the collection and save one. Also .find() is working too. Below is my code:
Model -> clientUser.js
var mongoose = require('mongoose');
var ClientUser = new mongoose.Schema({
firebaseUID :{type: String},
userName : { type : String},
displayName : { type : String}
});
ClientUser.index({firebaseUID: 1}, {unique: true});
module.exports = {
ClientUser : ClientUser
};
dependency.js
'use strict';
var mongoose = require('mongoose');
var ClientUser = mongoose.model('ClientUser');
var getNewClientUserModel = function () {
return mongoose.model('ClientUser');
};
module.exports = {
getNewClientUserModel : getNewClientUserModel
};
clientUser -> add.js
'use strict';
var dependency = require('./../../dependency');
var _ = dependency.getLodash();
var add = function (request, response) {
var firebaseUID = request.body.firebaseUID;
var userName = request.body.userName;
var displayName = request.body.displayName;
var newClientUser= dependency.getNewClientUserModel();
newClientUser.firebaseUID = firebaseUID;
newClientUser.userName = userName;
newClientUser.displayName = displayName;
if (!firebaseUID || !userName) {
response.send(400);
return null;
} else {
newClientUser.save(function (error,doc) {
if (!_.isEmpty(error)) {
response.send(500, {'message': 'Error in adding the Category', error: error});
} else {
response.send(200);
}
return null;
});
}
};
module.exports = {
add: add
};
app.js
var mongoose = require('mongoose');
mongoose.model('ClientUser', require('./models/clientUser').ClientUser);
/*
*Routes importing
*/
var ClientUser = {
'add' : require('./routes/clientuser/add').add
};
You need convert the schema into a Model you can work with, into your clientUser.js so pass it to mongoose.model(modelName, schema):
module.exports = mongoose.model('ClientUser', ClientUser);
Your problem is in /models/clientUser.js, you are exporting the schema. My suggestion is to export a model form that module. Also I donĀ“t understand the propose of dependency.js, why not use the model directly in your add handler ? Below is an suggestion that should work.
models/clientUser.js
var mongoose = require('mongoose');
var clientUserSchema = new mongoose.Schema({
firebaseUID :{type: String},
userName : { type : String},
displayName : { type : String}
});
clientUserSchema.index({firebaseUID: 1}, {unique: true});
var ClientUser = mongoose.model('ClientUser', clientUserSchema);
module.exports = {
ClientUser : ClientUser
};
routes/clientuser/add.js
'use strict';
var ClientUser = require('./clientUser').ClientUser;
var add = function (request, response) {
var firebaseUID = request.body.firebaseUID;
var userName = request.body.userName;
var displayName = request.body.displayName;
var newClientUser = new ClientUser({
firebaseUID: firebaseUID,
userName: userName,
displayName: displayName
});
if (!firebaseUID || !userName) {
return response.send(400);
}
newClientUser.save(function (error, doc) {
if (error) {
return response.send(500, { 'message': 'Error in adding the Category', error: error });
}
return response.sendStatus(200);
});
};
module.exports = {
add: add
};
app.js
/*
*Routes importing
*/
var ClientUser = {
'add' : require('./routes/clientuser/add').add
};

Resources