Javascript mongoose callback function when set data - javascript

Hello my problem is when I post base 64 images, I want to return a photo URL that's inside of my schema set return value
It always returns null and not set to photoUrl column
here is my schema
const ProductSchema = new Schema({
_id: {
type: Schema.Types.ObjectId,
default: require('mongodb').ObjectID
},
country: {
type: String,
required: [true, "country can't be null"]
},
photoUrl: {
type: String,
set: setImage
}
})
this my setter function
function setImage(base64) {
return uploadImage(base64,'/storage/products/');
}
and this is my uploadImage function on another page
const fs = require('fs');
const keys = require('../config/keys');
const mkdirp = require('mkdirp');
const uuidv4 = require('uuid/v4');
module.exports = {
get: function() {
let a = "Hello Node World!!!";
return a;
},
uploadImage: function(base64,storageURI,callback) {
const storagePathURI = '.' + storageURI;
mkdirp(storagePathURI, function (err) {
if (!err) {
var base64Data = base64.replace(/^data:image\/png;base64,/, "");
fs.writeFile(storagePathURI + uuidv4() + '.png', base64Data, 'base64')
return keys.baseStorageURI + storageURI + uuidv4() + '.png';
}
});
}
}
how can I map this URL to my photoUrl column when I insert or update the object?

Related

Cast to ObjectId failed for value XXX (type Object) at path \"depends_on\" for model \"Plan\"

I have an error message when I try to get a request from /api/subscriptions/5f108e96e55425340a7a7c6b of my project routes, this is the code from the get request:
index.js
const path = require('path');
const express = require('express');
const authRouter = require('./authRouter');
const apiRouter = require('./apiRouter');
const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser');
const auth = require('../middleware/auth');
const { changeSubscriptionStatus } = require('../controllers/subscriptionController');
const mtto = false;
module.exports = function (app) {
app.use(bodyParser.json({ limit: '100kb' }));
app.use(cookieParser());
app.use('/auth', authRouter);
app.use('/api', apiRouter);
// routing static assets from build
app.use(express.static(path.resolve(__dirname, '../../build'), {
index: false
}));
// webpack hot reloading hack
if (process.env.NODE_ENV === 'hot') {
const webpack = require('webpack');
const webpackConfig = require('../../webpack.config');
const compiler = webpack(webpackConfig);
app.use(require('webpack-dev-middleware')(compiler, {
noInfo: true, publicPath: webpackConfig.output.publicPath
}));
app.use(require('webpack-hot-middleware')(compiler));
}
app.post('/transactions/pending', changeSubscriptionStatus);
app.get('*', auth.optionalJwt, function (req, res, next) {
// console.log(req.originalUrl)
if (mtto) return res.sendFile(path.resolve(__dirname, '../../mtto/index.html'));
if (req.user) {
return res.sendFile(path.resolve(__dirname, '../../build/dashboard/index.html'));
}
return res.sendFile(path.resolve(__dirname, '../../build/public/index.html'));
});
};
subscription.js
const express = require('express');
const subscriptionRouter = express.Router();
const subscriptionController = require('../../controllers/subscriptionController');
const auth = require('../../middleware/auth');
const { Position } = require('../../constants/enums');
subscriptionRouter.get('/', subscriptionController.search);
subscriptionRouter.get('/byClient', auth.hasPosition(Position.ADMIN), subscriptionController.listByClient);
subscriptionRouter.post('/byEmail', subscriptionController.sendEmailInformation);
subscriptionRouter.post('/byemailactiv', subscriptionController.sendActivationCode)
subscriptionRouter.get('/:subscriptionId', subscriptionController.detail);
subscriptionRouter.get('/status/:subscriptionId', subscriptionController.statusDetail)
subscriptionRouter.post('/', auth.companyIsActive, subscriptionController.create);
subscriptionRouter.post(
'/renew',
auth.companyIsActive,
subscriptionController.renew
)
subscriptionRouter.delete('/:subscriptionId', subscriptionController.cancel);
subscriptionRouter.put('/:subscriptionId', auth.companyIsActive, subscriptionController.edit);
subscriptionRouter.post('/status', subscriptionController.editStatusSubscrition)
subscriptionRouter.post('/:subscriptionId/addon', auth.companyIsActive, subscriptionController.contractAddon);
subscriptionRouter.put('/:subscriptionId/addon/:planId', auth.companyIsActive, subscriptionController.editAddonSubscription);
subscriptionRouter.delete('/:subscriptionId/addon/:planId', subscriptionController.cancelAddonSubscription);
module.exports = subscriptionRouter;
And here is the detail function code from subscriptionController file:
subscriptionController.js
const Client = require("../models/client");
const Subscription = require("../models/subscription");
const defaults = require("../constants/defaults");
const { SubscriptionStatus, Position } = require("../constants/enums");
const Plan = require("../models/plan");
const Service = require("../models/service");
const Provider = require("../models/provider");
const Account = require("../models/account");
const notMissing = require("../util/notMissing");
const ApiError = require("../util/ApiError");
const axios = require("axios");
const exchange = require("../util/exchange");
const { ExternalService } = require("../services");
const mailgun = require("mailgun-js")({
apiKey: process.env.MAILGUN_API_KEY,
domain: process.env.MAILGUN_DOMAIN,
});
const detail = (req, res, next) => {
const isCTAdmin = req.user.position >= Position.CT;
let subscriptionQuery;
if (isCTAdmin) {
subscriptionQuery = Subscription.findOne({
_id: req.params.subscriptionId,
});
} else {
subscriptionQuery = Subscription.findOne({
_id: req.params.subscriptionId,
company: req.user.company.id,
});
}
subscriptionQuery
.populate("plan service provider client addons.plan addons.options company")
.exec()
.then((subscription) => {
if (!subscription)
return Promise.reject(ApiError.NotFound("Subscription not found"));
return Promise.all([subscription, subscription.availableAddons()]);
})
.then(async ([subscription, availableAddons]) => {
let subscriptionObject = subscription.toObject();
subscriptionObject.addons = subscriptionObject.addons.filter(
(a) => a.status === SubscriptionStatus.ACTIVE
);
// Populate available addons
subscriptionObject.availableAddons = availableAddons
.map((a) => a.toObject())
.filter((a) =>
subscription.client.authorized_segments.includes(a.segment)
);
// Get dynamic prices for addons
subscriptionObject.addons.forEach((a, index) => {
const plan = subscription.addons[index].plan;
a.plan.price = isCTAdmin
? plan.cost
: plan.price(req.user.company.rates, plan.currency);
});
// Set dynamic price
subscriptionObject.availableAddons.forEach((p, index) => {
const plan = availableAddons[index];
p.price = isCTAdmin
? plan.cost
: plan.price(req.user.company.rates, plan.currency);
});
// Set price for subscription itself
const plan = subscription.plan;
subscriptionObject.plan.price = isCTAdmin
? plan.cost
: plan.price(req.user.company.rates, plan.currency);
delete subscriptionObject.plan.cost;
// Set Status
if (subscriptionObject.provider.type === "kaspersky") {
if (subscriptionObject.service.package_type === "Suscripcion") {
const response = await getToken({
type: "get",
url: `${process.env.API_PUBLICA}/suscripciones/kaspersky/${subscriptionObject.identifier}`,
});
let dataObject = {
ActivationCode: response.data.ActivationCode,
status: response.data.Status,
};
subscriptionObject.statusSubscription = dataObject;
return subscriptionObject;
} else {
const response = await getToken({
type: "get",
url: `${process.env.API_PUBLICA}/suscripciones/kaspersky/async/status/${subscriptionObject.identifier}`,
});
let dataObject = {
descripcion: response.data.GetOrderStatusResult.Data.Description,
status: response.data.GetOrderStatusResult.Data.ProcessingStatus,
};
subscriptionObject.statusSubscription = dataObject;
return subscriptionObject;
}
}
// if (subscriptionObject.provider.type === 'bind') subscriptionObject.plan.price = subscriptionObject.metadata.suscriptionData.Quote / 1.16
// subscriptionObject.company = subscription.company.info;
// return subscriptionObject
})
.then((subscription) => res.json(subscription))
.catch(next);
};
plan.js
const mongoose = require("mongoose");
const moment = require("moment");
const ObjectId = mongoose.Schema.ObjectId;
const {
PlanSegment,
PLAN_SEGMENTS,
CURRENCIES,
SubscriptionStatus,
VENDOR_ACCOUNT_TYPES,
PERIODS,
Period,
} = require("../constants/enums");
const Big = require("big.js");
const commonModelOptions = require("../util/commonModelOptions");
const SubscriptionChange = require("./subscriptionChange");
const PlanSchema = new mongoose.Schema(
{
name: { type: String, required: true },
description: { type: String, required: true },
service: { type: ObjectId, ref: "Service" },
identifier: { type: String, index: true }, // External ID by provider
cost: Number,
prices_by_quantity: {
type: [
{
min_q: Number,
max_q: Number,
price: Number,
band: String,
ct_price: Number,
ct_key: String,
},
],
default: [],
},
currency: { type: String, enum: CURRENCIES, required: true },
unit: String,
accountType: { type: String, enum: VENDOR_ACCOUNT_TYPES, required: true },
period: { type: String, enum: PERIODS, default: Period.month },
is_addon: { type: Boolean, default: false },
depends_on: { type: [{ type: ObjectId, ref: "Plan" }], default: [] },
options: { type: mongoose.Schema.ObjectId, ref: "Options" },
segment: {
type: String,
enum: PLAN_SEGMENTS,
default: PlanSegment.PRIVATE,
},
ct_key: { type: String, default: "CARGO100" },
inmutable: { type: Boolean, default: false },
is_incomplete: { type: Boolean, default: false },
subscription_limit_min: { type: String, defaul: null },
subscription_limit_max: { type: String, defaul: null },
type: { type: String, default: null },
},
commonModelOptions
);
And I get this message:
// 20230116112216
// http://localhost:4040/api/subscriptions/5f108e96e55425340a7a7c6b
{
"message": "Cast to ObjectId failed for value \"" (type Object) at path \"depends_on\" for model \"Plan\"",
"ok": false
}
How can I solve this?

Mongoose update update nested object inside an array

I'm trying to query and update an element in the rosters array ( roster.schedule.monday.start) & then update the value in this example.
monday.start these two keys need to be dynamic
I think the approach would be something like this
Find document by _id
find matching object in array by _id
update nested values
I have tried this below with no luck, could anybody assist in this problem
many thanks
// Mongoose query
exports.updateRoster = (req, res) => {
const editDay = req.body.day;
const value = req.body.valueOfEntry;
const userId = req.body.id;
const rosterId = req.body.rosterId;
const startPerieod = req.body.time;
let dynObj = {
["rosters.$.schedule.$." + editDay + ".$." + startPerieod]: value,
};
Carer.updateOne({ "rosters._id": rosterId }, { $set: dynObj }).exec(
(err, roster) => {
if (err) {
return res.status(400).json({
error: err,
});
}
res.json(roster);
}
);
};
// Schema
const mongoose = require("mongoose");
const { ObjectId } = mongoose.Schema;
const carersSchema = new mongoose.Schema({
rosters: [
{
schedule: {
monday: {
start: { type: String },
finish: { type: String },
notes: { type: String },
},
],
});
module.exports = mongoose.model("Carers", carersSchema);
Try using $set and array filters like in the link
Carer.findOneAndUpdate({_id: carerId},
{
"$set": {[`rosters.$[outer].schedule.${editDay}.${startPerieod}`]: value}
},
{
"arrayFilters": [{ "outer._id": roasterId }]
},
function(err, response) {
if(err) console.log(err)
console.log(response)
})

how to update 2nd schema using node js (mongdb)

I am trying to update my 2nd schema which having reference in first schema
ownerSchema.js
var ownerSchema = Schema({
fname : String,
lname : String,
shopPlace : {
type: Schema.Types.ObjectId,
ref: 'Shop'
}
});
var Owner = mongoose.model('Owner', ownerSchema);
shopSchema.js
var shopSchema = Schema({
shopName : String,
location : String,
startDate : Date,
endDate : Date
});
var Shop = mongoose.model('Shop', shopSchema);
so I am trying to update my schema like this
const update = async (req, res) => {
const { id } = req.params;
let update = {};
if (req.body.fname) update.fname = req.body.fname;
if (req.body.lname) update.lname = req.body.lname;
if (req.body.shopPlace.shopName) update.shopPlace.shopName = req.body.shopPlace.shopName;
if (req.body.shopPlace.location) update.shopPlace.location = req.body.shopPlace.location;
let newOwmer = new Owner.updateOne(
{ ownerId: id },
{
$set: update,
},
{ runValidators: true }
);
};
I am trying to update shop but its not working and where am i wrong i dont know
const update = async (req, res) => {
const { id } = req.params;
let update = {};
let updateShop = {}
if (req.body.fname) update.fname = req.body.fname;
if (req.body.lname) update.lname = req.body.lname;
if (req.body.shopPlace.shopName) updateShop.shopPlace.shopName = req.body.shopPlace.shopName;
if (req.body.shopPlace.location) updateShop.shopPlace.location = req.body.shopPlace.location;
// get shopPlace _id from Owner
const { shopPlace } = await Owner.findOneAndUpdate(
{ _id: id },
{
$set: update,
},
{ new:true}
);
// here you must have the document you just updated. Just recover the id of the shop to modify it in turn
// update shop
let newShop = await Shop.findOneAndUpdate(
{ _id: shopPlace },
{
$set: updateShop,
},
{new:true}
);
};

Nodejs - async function - TypeError: Cannot set property 'temperature' of undefined

JavaScript beginner here, I'm trying to get something going in Nodejs using hap-nodejs module.
My Main file looks like this:
const config = require('../config');
const Syno = require('synology');
const docker = new Docker(config.dockerode);
const storage = require('node-persist');
const os = require('os');
storage.initSync();
const {Bridge, uuid, Categories} = require('hap-nodejs');
const TemperatureSensorAccessory = require('./TempGageAccessory');
const name = config.bridge.deviceName.replace('$hostname', os.hostname()).replace(/\./, ' ');
const bridge = new Bridge(name, uuid.generate('Remote Bridge'));
bridge.publish({
username: config.bridge.mac,
port: config.bridge.port,
pincode: config.bridge.pincode,
category: Categories.BRIDGE
});
async function publishSynology()
{
const dev = new TemperatureSensorAccessory('NAS_SYS_TEMP');
bridge.addBridgedAccessories({
accessory: dev.getAccessory()
});
}
publishSynology();
and my /TempGageAccessory.js file where the problem is this one here:
const {Accessory, Service, Characteristic, uuid, Categories} = require('hap-nodejs');
const Syno = require('synology');
const {emitter, docker} = require('./DockerKit');
module.exports = class TemperatureSensorAccessory {
constructor(name) {
console.log('Constructing ' + name);
this.TemperatureSensor = {
name,
model: 'Synology NAS Temperature Sensor',
category: Categories.SENSOR,
description: name,
setTemperature: function () {
let syno = new Syno({
host : '10.0.0.1',
port : '5656',
secure : 'true',
user : 'user',
password: 'password'
});
syno.query('/webapi/entry.cgi', {
api : 'SYNO.Core.System',
version: 1,
method : 'info'
}, function(err, data) {
if (err) return console.error(err);
console.log(data['data']['sys_temp']);
this.temperature = parseFloat(data['data']['sys_temp']);
return parseFloat(data['data']['sys_temp']);
});
},
temperature: 0.0,
getTemperature: async function () {
console.log('[' + name + '] Getting Temperature' + this.temperature);
return this.temperature;
},
uuid: uuid.generate('hap-nodejs:accessoires:temperaturesensor:synology:' + name),
accessory: null
};
const that = this;
that.TemperatureSensor.setTemperature();
that.getAccessory().getService(Service.TemperatureSensor).getCharacteristic(Characteristic.On).updateValue(that.TemperatureSensor.temperature);
}
getAccessory() {
if (!this.TemperatureSensor.accessory) {
let acc;
acc = new Accessory(this.TemperatureSensor.name, this.TemperatureSensor.uuid);
acc.username = '8a:bc:80:74:de:16';
acc.pincode = '123-45-678';
acc
.addService(Service.TemperatureSensor, this.TemperatureSensor.name)
.getCharacteristic(Characteristic.CurrentTemperature)
.on('get', async(cb) => {
// return our current value
cb(null, await this.TemperatureSensor.getTemperature());
});
this.TemperatureSensor.accessory = acc;
return acc;
} else return this.TemperatureSensor.accessory;
}
};
I got everything almost there, my rest call is working fine and I'm returning my data. But when I try to assign the result of my query to property temperature I get the following error:
TypeError: Cannot set property 'temperature' of undefined
Please, can someone explain what I'm doing wrong ? I'm no Javascript Developer, first time playing with it coming from C#/Python.
Beginner error, fixed by refereeing to the correct object.

Promise in cron job

I try to run the code without success.
Only the first call works in start of node.
Here is my current code:
const Product = require('../models/Product');
const Price = require('../models/Price');
const cron = require('node-cron');
const amazon = require('amazon-product-api');
const util = require('util');
const _ = require('underscore')
/**
* Cron job
* Tracking price
*/
exports.track = () => {
cron.schedule('* * * * *', () => {
const client = amazon.createClient({
awsId: process.env.AWS_ID,
awsSecret: process.env.AWS_SECRET,
assocId: process.env.AWS_TAG
});
Promise.all([Product.getAsin()])
.then(([asin]) => {
let listId = _.pluck(asin, '_id');
let listAsin = _.pluck(asin, 'asin');
if (asin.length === 0) {
return
}
client.itemLookup({
idType: 'ASIN',
itemId: listAsin,
domain: 'webservices.amazon.fr',
responseGroup: 'ItemAttributes,OfferFull,SalesRank'
}).then((results) => {
for(i=0; i<listId.length; i++){
results[i].id = listId[i];
}
for(res of results) {
Price.addPrice({
asin: res.ASIN[0],
product: res.id,
salePrice: res.Offers[0].Offer[0].OfferListing[0].Price[0].Amount[0],
})
}
console.log(listId);
Product.makeUpdate(listId);
}).catch(function(err) {
console.log(err);
console.log(util.inspect(err, true, null));
});
})
.catch((err) => {
console.log(err);
})
})
}
Requests to MongoDB are asynchronous.
Product
const mongoose = require('mongoose');
mongoose.Promise = Promise;
const _ = require('underscore');
const moment = require('moment');
const productSchema = new mongoose.Schema({
name: String,
domain: String,
originUrl: { type: String, unique: true },
check: { type: Number, default: 0 },
ean: String,
asin: String
}, { timestamps: true });
Object.assign(productSchema.statics, {
getAsin() {
return this.find(
{ updatedAt: { $lt: oneMin },
asin: { $ne: null }
}
).limit(10)
.select({ asin: 1 })
.exec()//.then((tuples) => _.pluck(tuples, 'asin'))
},
makeUpdate(id) {
console.log('list des ID updated => ' + id);
return this.update({ _id: { $in: id } }, { $inc : { "check": 1 } } , {multi: true}).exec();
}
});
const Product = mongoose.model('Product', productSchema);
module.exports = Product;
const oneMin = moment().subtract(1, 'minutes').format();
Also, since I'm absolutely new to JavaScript and Node.js in general, any best practices or general tips will be greatly appreciated! :)

Categories

Resources