NodeJs - mongoose function always return null - node.js

I am new to nodeJs and i am trying to return apikey from the function saveApi but it always returns null. Can you help me with that?
var saveApi = async (email) => {
const apikeyvalue = apigen.create().apiKey;
console.log("key",apikeyvalue)
const apikey = require("../models/api");
var finalkey=null
try {
let key = new apikey({ email: email, apikey: apikeyvalue })
finalkey = await key.save();
} catch (e) {
throw new ProductCreateError();
}
return finalkey.apikey
};
Here is the definition of my apikey model
var mongoose=require('mongoose');
var apiSchema= new mongoose.Schema({
email:String,
apikey:String
});
module.exports = mongoose.model(
'apikey', apiSchema, 'apikeys');
and here is the function call to saveApi()
var api = saveApi.then(obj.username)

Related

I want to send specific parameters and all entries of json api as a respone. It is showing Http_Header error. How to do it?

const fetch = require("node-fetch");
const express = require('express');
const app = express();
const mongoose = require('mongoose');
mongoose.connect('mongodb://127.0.0.1:27017/todoApi');
mongoose.connection.on('error', e=>{
console.log('connection failed');
});
mongoose.connection.on('connected', connected=>{
console.log('connection successful to the database');
});
const todoSchema = new mongoose.Schema({
userId:{
type: Number,
},
id:{
type: Number
},
title:{
type: String
},
completed:{
type:Boolean
}
});
const todoModel = mongoose.model("todoModel", todoSchema);
app.get("/todo", (request, res)=>{
async function getToDo(){
const todoData = await fetch('https://jsonplaceholder.typicode.com/todos');
const response = await todoData.json();
for(let i = 0; i<response.length;i++){
let kuchbhi;
const todos = new todoModel({
userId: response[i]["userId"],
id: response[i]["id"],
title: response[i]["title"],
completed: response[i]["completed"]
})
res.send(response[i]);
}
console.log(response[0]['userId']);
}
getToDo();
})
you are using res.send inside for loop. The data from get request is sent only one time.
Instead of using res.send inside loop, use to loop to push() to add elements in the array, use res.send after the loop to share this array.
app.get("/todo", (request, res)=>{
async function getToDo(){
const todoData = await fetch('https://jsonplaceholder.typicode.com/todos');
const response = await todoData.json();
let responseArray = [];
for(let i = 0; i<response.length;i++){
let kuchbhi;
const todos = new todoModel({
userId: response[i]["userId"],
id: response[i]["id"],
title: response[i]["title"],
completed: response[i]["completed"]
})
responseArray.push(response[i]);
}
res.send(responseArray);
}
getToDo();
})

Multi-tenancy with mongoose and express

I am working on a MERN SaaS application and I have read all manner of documents on multi-tenancy, where the goal is to create a layer of data isolation above the level of the user. putting all the info together I came about this solution which suggests making use of "continous-local-storage" However, after implementing it, I can't really get it to work, all I have seems logically right, I really can't figure out the issue. After implementation, my application refuses to load data from the database...
//lib/storage.js
const createNamespace = require('continuation-local-storage').createNamespace;
const namespaceName = ('request');
const ns = createNamespace(namespaceName);
const bindCurrentNamespace=function(req, res, next){
ns.bindEmitter(req);
ns.bindEmitter(res);
ns.run(() => {
next();
});
}
const setCurrentTenantId=function(tenantId){
return ns.set('tenantId', tenantId);
}
const getCurrentTenantId=function(){
return ns.get('tenantId');
}
module.exports ={
bindCurrentNamespace:function(){},
setCurrentTenantId:function(){},
getCurrentTenantId:function(){}
}
Sever.js
**********
// some code above
const storage= require('./lib/storage')
// multitenant logic
const BindCurrentNamespace = storage.bindCurrentNamespace
app.use(BindCurrentNamespace);
app.use((req, res, next) => {
// Get current user from session or token
const user = req.user
// Get current tenant from user here
// Make sure its a string
const tenantId = user.organization._id.toString()
setCurrentTenantId(tenantId);
next();
});
/lib/multiTenant.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const storage = require('./storage');
const GetCurrentTenantId = storage.getCurrentTenantId
const tenantModel = function (name, schema, options) {
return (props = {}) => {
schema.add({ tenantId: String });
const Model = mongoose.model(name, schema, options);
const { skipTenant } = props;
if (skipTenant) return Model;
Model.schema.set('discriminatorKey', 'tenantId');
const tenantId = GetCurrentTenantId;
const discriminatorName = `${Model.modelName}-${tenantId}`;
const existingDiscriminator = (Model.discriminators || {})[discriminatorName];
return existingDiscriminator || Model.discriminator(discriminatorName, new Schema({}));
};
}
const tenantlessModel = function (name, schema, options) {
return () => mongoose.model(name, schema, options);
}
module.exports={
tenantModel:function(){},
tenantlessModel:function(){}
}
Modified Schema
// Employee schema
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const Tenant= require('../lib/multiTenant')
const TenantModel=Tenant.tenantModel;
//create Schema
const EmployeeSchema = new mongoose.Schema({
name: String,
department: String,
origin: String,
wages:Number,
overtime:{type:Number,
default:0},
joinDate: String,
attendances: Object
},{timestamps:true});
const Employee=TenantModel("Employee", EmployeeSchema,'employee001');
module.exports=Employee
Usage
// #desc Get all Employee
//#routes Get/api/v1/employee
//#acess Public
exports.getAllEmployee = asyncHandler(async (req, res, next) => {
Employee().find({}, null, {sort: {name: 1}}, function(err, employees){
if(err){
res.status(500);
res.send(err);
} else {
res.json(employees);
}
});
});

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');
}
});
});

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
};

Mongoose not returning document from mongo

I am trying to get Mongoose to query my mongo instance for a specific document (using the _id attribute). I currently have the following route:
router.get('/document/', function (req, res) {
var getDocuments = function (callback) {
var options = { server: { socketOptions: { keepAlive: 1000 } } };
var connectionString = 'mongodb://user:password#server:27017/db';
var pID = req.query.id;
pID = pID.trim();
console.log(pID);
var documentArray = [];
// Connected handler
Mongoose.connect(connectionString, function (err) {
var db = Mongoose.connection.useDb('db');
var pCollection = db.collection("collection");
//grab all items from pCollection
pCollection.find({ '_id': pID }, function (error, pDocument) {
if (error) {
console.log(error);
}
if (pDocument) {
// res.send(JSON.stringify(pDocument));
console.log(pDocument);
}
else {
console.log("nothing");
}
});
db.close();
});
};
getDocuments(function () {
});
});
The result returned is not a json document and does not seem to return a usable value. What am I doing wrong? Thanks for any help in advance!
EDIT:
I went back and changed the route to the following:
router.get('/document/', function (req, res) {
var pID = req.query.id;
pID = pID.trim();
console.log(pID);
Document.findById(pID, function (error, document) {
if (error) {
console.log(error);
}
else {
console.log(document);
}
});
});
I also created the following model:
var mongoose = require('mongoose');
var DocumentSchema = require('../schemas/documents');
var Document = mongoose.model('documents', DocumentSchema, 'Documents');
module.exports = Document;
And used the following schema:
var mongoose = require('mongoose');
var DocumentSchema = new mongoose.Schema({
documenttPK: String,
locationID: String,
docName: String,
SerialNumber: String,
documentID: String,
dateEntered: Date,
activeFlag: Boolean
});
module.exports = DocumentSchema;
My app.js makes a single call to a db file:
var mongoose = require('mongoose');
mongoose.connect('mongodb://user:password#server:27017/db');
But the result is still null. Is something wrong with the above code?

Resources