Exception while simulating the effect of invoking 'deals.insert' error - javascript

I'm trying to submit form data to the database with react and meteor.
I have a AddDeal component for the form and a collection for the deals and also a method inside it.
Error
Exception while simulating the effect of invoking 'deals.insert'
ReferenceError: _id is not defined
Getting the error: ID is required when submit is clicked.
I don't know how to handle the _id when inserting.
Here is my code, and thanks for helping!
onSubmit(e) function
onSubmit(e) {
e.preventDefault();
const title = this.state.title.trim();
const description = this.state.description;
const category = this.state.category;
const location = this.state.location;
const price = this.state.price.trim();
e.preventDefault();
if (title, description, category, location, price) {
Meteor.call('deals.insert', title, description, category, location, price);
}
alert('Title is: ' + this.state.title + 'Description is: ' + this.state.description + 'Category is: ' + this.state.category
+ 'Location is: ' + this.state.location + 'Price: ' + this.state.price);
this.setState({
title: '',
description: '',
category: 'technology',
location: 'USA',
price: '0.00'
});
}
Insert method
export const Deals = new Mongo.Collection('deals');
if (Meteor.isServer) {
Meteor.publish('deals', function () {
return Deals.find({ userId: this.userId });
});
}
Meteor.methods({
'deals.insert'(_id, title, description, category, price, location) {
if (!this.userId) {
throw new Meteor.Error('not-allowed');
}
new SimpleSchema({
_id: {
type: String,
min: 1
},
title: {
type: String,
optional: true
},
description: {
type: String,
optional: true
},
category: {
type: String,
optional: true
},
location: {
type: String,
optional: true
},
price: {
type: Number,
optional: true
}
}).validate({
});
Deals.insert({
_id,
title,
description,
category,
location,
price,
createdAt: Date(),
userId: this.userId
});
}
});

On deals.insert you are validating the parameter this.userId instead of this._id?
I think you nedd to change this:
'deals.insert'(_id, title, description, category, price, location) {
if (!this.userId) {
throw new Meteor.Error('not-allowed');
}
...
to this:
'deals.insert'(_id, title, description, category, price, location) {
if (!this._id) {
throw new Meteor.Error('not-allowed');
}

Related

Mongoose - CastError Cast to string failed for value "Object"

I have Mongoose CastError issue. I made a nodeJs API. At the specific route, it returns data appended with some other data. I saw many fixes available here but my scenario is different.
Here is my model and the problem occurs at fields property.
const deviceSchema = new Schema({
device_id: { type: String, required: true },
user_id: { type: Schema.Types.ObjectId, ref: 'User', require: true },
location_latitude: { type: String, default: '0' },
location_longitude: { type: String, default: '0' },
fields: [{ type: String }],
field_id: { type: Schema.Types.ObjectId, ref: 'Field', required: true },
timestamp: {
type: Date,
default: Date.now,
},
});
and my controller is
exports.getAllDevices = async (req, res) => {
try {
let devices = await Device.find({})
.sort({
timestamp: 'desc',
})
.populate('user_id', ['name']);
// Let us get the last value of each field
for (let i = 0; i < devices.length; i++) {
for (let j = 0; j < devices[i].fields.length; j++) {
if (devices[i].fields[j] !== null && devices[i].fields[j] !== '') {
await influx
.query(
`select last(${devices[i].fields[j]}), ${devices[i].fields[j]} from mqtt_consumer where topic = '${devices[i].device_id}'`
)
.then((results) => {
************** Problem occurs here **************
if (results.length > 0) {
devices[i].fields[j] = {
name: devices[i].fields[j],
last: results[0].last,
};
} else {
devices[i].fields[j] = {
name: devices[i].fields[j],
last: 0,
};
}
************** Problem occurs here **************
});
}
}
}
// Return the results
res.status(200).json({
status: 'Success',
length: devices.length,
data: devices,
});
} catch (err) {
console.log(err);
res.status(500).json({
error: err,
});
}
};
It actually gets data from InfluxDB and appends it to fields property which was fetched from MongoDB as mentioned in my model. But it refused to append and CastError occurs.
After addition, it will look like this
I can't resolve this error after trying so many fixes. I don't know where I'm wrong. Please suggest to me some solution for this.
I can see you are not using devices variable as Mongoose Document. devices is an array of Documents.
I would like to suggest you to use lean() function to convert from Document to plain JavaScript object like
let devices = await Device.find({})
.sort({
timestamp: 'desc',
})
.populate('user_id', ['name'])
.lean();

How to update existing object with additional data

The project is created with nodejs and mongoose. What I am trying to do is to update the existing model with addition data (which is a comment, in that case).
This is the model and its methods:
const bugSchema = new Schema({
title: {
type: String,
required: true
},
description: {
type: String,
required: true
},
date: {
type: String,
required: true
},
time: {
type: String,
required: true
},
assignedTo: {
type: String,
required: true
},
assignedBy: {
type: String,
required: true
},
status: {
type: String,
required: true
},
priority: {
type: String,
required: true
},
comments: {
comment:[
{
user:{
type: String,
required: true
},
content: {
type: String,
required: true
}
}
]
}
});
bugSchema.methods.addComment = function(comment){
const username = comment.user;
const content = comment.content;
console.log(comment);
const updatedComments = [...this.comments];
updatedComments.push({
user : username,
content: content
});
this.comments = updatedComments;
return this.save();
};
The controller, which is passing the information from the form:
exports.postComment = (req,res,next) =>{
const bugId = req.body.bugID;
const name = req.session.user.fullName;
const content = req.body.content;
const prod = {name, content};
Bug.findById(bugId).then(bug =>{
return bug.addComment(prod);
})
.then(result =>{
console.log(result);
});
};
I am getting a following error:
(node:3508) UnhandledPromiseRejectionWarning: TypeError: this.comments is not iterable
(node:3508) UnhandledPromiseRejectionWarning: TypeError: this.comments is not iterable
The error indicate you're trying to iterable a type of data which does NOT has that capability.
You can check that printing the type:
console.log(typeof this.comments)
Or even, priting the whole object:
console.log(this.comments)
as you can see, in both cases you're getting an object, not a list (how you spect)
So you can do 2 things:
1- Iterable a list
this.comments is an object but into that object you have the list you want, so just use the list instead.
bugSchema.methods.addComment = function(comment){
const username = comment.user;
const content = comment.content;
console.log(comment);
//const updatedComments = [...this.comments];
const updatedComments = [...this.comments.comment];
updatedComments.push({
user : username,
content: content
});
this.comments = updatedComments;
return this.save();
};
Or you can modify your schema making the comments a list instead of an object
2- comments as list in schema
Define the comments attribute as a list
const bugSchema = new Schema({
title: {
type: String,
required: true
},
description: {
type: String,
required: true
},
...
...,
comments:[
{
user:{
type: String,
required: true
},
content: {
type: String,
required: true
}
}
]
});
And then, try to iterable it as how you been doing
bugSchema.methods.addComment = function(comment){
const username = comment.user;
const content = comment.content;
console.log(comment);
const updatedComments = [...this.comments];
updatedComments.push({
user : username,
content: content
});
this.comments = updatedComments;
return this.save();
};
I am not sure but comments is an object and not an array so you can't push using [...this.comments] and I think it is the comment you want to push?
const updatedComments = [...this.comment];
updatedComments.push({
user : username,
content: content
});
this.comment = updatedComments;
From your schema comments is not an array. you are trying to spread an object into an array. const updatedComments = [...this.comments]; also push works on array.
try to modify your schema definitions by declaring the commentSchema outside the bugSchema.
const commentSchema = new Schema({
user:{
type: String,
required: true
},
content: {
type: String,
required: true
}
})
const bugSchema = new Schema({
comments: {
type: [commentSchema]
}
})
Bug.findByIdAndUpdate(bugId, {$push: {comments: newComment}})
Don't use findByIdAndUpdate Mongoose method, you better use save
it is written here https://mongoosejs.com/docs/tutorials/findoneandupdate.html
The findOneAndUpdate() function in Mongoose has a wide variety of use cases. You should use save() to update documents where possible, but there are some cases where you need to use findOneAndUpdate(). In this tutorial, you'll see how to use findOneAndUpdate(), and learn when you need to use it.
Below a router example
router.put('/items', (req, res) => {
if (!req.body._id || !req.body.title) {
return res.status(501).send({ message: 'Missing parameters, or incorrect parameters' });
}
return itemModel.findOne({ _id: req.body._id }, (err, item) => {
if (err) {
return res.status(500).send({
message: err
});
}
item.title = req.body.title; // <------------- You rewrite what was before stored on title attribute
return item.save((err, item) => { // <------------- You save it, this is not gonna create a new one, except if it doesn't exist already
if (err) {
return res.status(400).send({
message: 'Failed to update item'
});
} else {
return res.status(200).send({
message: 'Item update succesfully',
data: item
});
}
});
});
});

Edit operation failing in Node

This is my code:
router.post('/update-posting', (req, res, next) => {
Account.findById(req.user._id)
.then(doc => {
var type = [];
if (req.body.full !== undefined) {
type.push('full');
}
if (req.body.part !== undefined) {
type.push('part');
}
if (req.body.seasonal !== undefined) {
type.push('seasonal');
}
if (req.body.temporary !== undefined) {
type.push('temp');
}
var title = req.body.title;
var salary = req.body.salary;
var timeline = req.body.timeline;
var experience = req.body.experience;
var description = req.body.description;
var duties = req.body.duties;
doc.postings[req.body._id] = {
_id: req.body._id,
title: title,
type: type,
salary: salary,
timeline: timeline,
description: description,
duties: duties,
experience: experience,
};
doc.save(r=>console.log(r));
})
.then(() => res.redirect('/employer/booth-edit'))
.catch(e => console.log(e))
});
And here's the model:
var mongoose = require('mongoose');
var plm = require('passport-local-mongoose');
var accountSchema = new mongoose.Schema({
// username (comes with passport): email; -> just for reference.
accType: String,
fullName: String,
displayName: String,
companyName: String,
contactPersonFullName: String,
companyWebsite: String,
city: String,
province: String,
postalCode: String,
phoneNumber: String,
hiringRegion: [], // TODO
description: String,
logo: [],
workingWithEOESC: Boolean,
industry: String,
phone: String,
ageGroup: String,
education: String,
lookingForWork: String,
employmentStatus: String,
resume: [],
mainWorkExp: String,
boothVisits: Number,
postings: []
});
accountSchema.plugin(plm);
module.exports = mongoose.model('account', accountSchema);
What I'm doing is trying to update an object in the postings array. Now here's the weird part. When I console log the result before doc.save() I get the updated version... And when I console log the response from doc.save() I get null... I'm sure that's a small bug but I cannot see it anywhere.
All fields are coming from the req.body object correctly.
Here are the logs.
Original object:
{ _id: 0,
title: 'Web developer',
type: [ 'full', 'seasonal' ],
salary: '14$',
timeline: '3 months',
description: 'tada',
duties: 'tada',
experience: '5 years' }
Updated object:
{ _id: '0',
title: 'Car mechanic',
type: [ 'part', 'temp' ],
salary: '50$',
timeline: '2 weeks',
description: 'desc',
duties: 'resp',
experience: '4 years' }
doc.save() response:
null
What's more interesting, this is the code I'm using for "creating" a job posting. It's almost the same code, and it works perfectly well:
router.route('/add-posting')
.get((req, res, next) => {
res.render('users/employer/add-posting', {
title: 'Employer Booth - Add Job Posting',
user: req.user
});
})
.post((req, res, next) => {
// Determining type of work.
var type = [];
if (req.body.full !== undefined) {
type.push('full');
}
if (req.body.part !== undefined) {
type.push('part');
}
if (req.body.seasonal !== undefined) {
type.push('seasonal');
}
if (req.body.temporary !== undefined) {
type.push('temp');
}
var title = req.body.title;
var salary = req.body.salary;
var timeline = req.body.timeline;
var experience = req.body.experience;
var description = req.body.description;
var duties = req.body.duties;
Account.findById(req.user._id)
.then(doc => {
doc.postings.push({
_id: doc.postings.length,
title: title,
type: type,
salary: salary,
timeline: timeline,
description: description,
duties: duties,
experience: experience,
});
doc.save();
})
.then(() => res.redirect('/employer/booth-edit'))
.catch(e => console.log(e));
});
They way you're doing it may work. But mongo has already provided you with update or findOneAndupdate methods. I'd suggest you to use them.
Your query would be easy to understand and debug when needed.
Try something like
db.collection.update({_id: .user._id},{$push :{postings: yourObject}})
I just remembered I had this issue before. Turns out that to update an array we need to do this:
doc.postings.set(req.body._id, {
_id: req.body._id,
title: title,
type: type,
salary: salary,
timeline: timeline,
description: description,
duties: duties,
experience: experience,
});
I remember reading an issue on that. Will add the link if I find it again.
We need to use the .set method instead of the = operator.

node Sequelize how to write static functions

I have experience in writing statics functions in moongose like
var mongoose =require('mongoose');
var Schema = mongoose.Schema;
var adminSchema = new Schema({
fullname : String,
number : Number,
email: String,
auth : {
username: String,
password : String,
salt: String
}
});
adminSchema.statics.usernameInUse = function (username, callback) {
this.findOne({ 'auth.username' : username }, function (err, doc) {
if (err) callback(err);
else if (doc) callback(null, true);
else callback(null, false);
});
};
here usernameInUse is the function I wana write but using sequelize for mysql database
my model
/*
This module is attendant_user table model.
It will store attendants accounts details.
*/
"use strict";
module.exports = function(sequelize, DataTypes) {
var AttendantUser = sequelize.define('AttendantUser', {
username : {
type : DataTypes.STRING,
allowNull : false,
validate : {
isAlpha : true
}
},{
freezeTableName : true,
paranoid : true
});
return AttendantUser;
};
How to add statics function here..??
Well, you can easily use Expansion of models
var User = sequelize.define('user', { firstname: Sequelize.STRING });
// Adding a class level method
User.classLevelMethod = function() {
return 'foo';
};
// Adding an instance level method
User.prototype.instanceLevelMethod = function() {
return 'bar';
};
OR in some cases you may use getter and setter on your models. See the docs:
A) Defining as part of a property:
var Employee = sequelize.define('employee', {
name: {
type : Sequelize.STRING,
allowNull: false,
get : function() {
var title = this.getDataValue('title');
// 'this' allows you to access attributes of the instance
return this.getDataValue('name') + ' (' + title + ')';
},
},
title: {
type : Sequelize.STRING,
allowNull: false,
set : function(val) {
this.setDataValue('title', val.toUpperCase());
}
}
});
Employee
.create({ name: 'John Doe', title: 'senior engineer' })
.then(function(employee) {
console.log(employee.get('name')); // John Doe (SENIOR ENGINEER)
console.log(employee.get('title')); // SENIOR ENGINEER
})
B) Defining as part of the model:
var Foo = sequelize.define('foo', {
firstname: Sequelize.STRING,
lastname: Sequelize.STRING
}, {
getterMethods : {
fullName : function() { return this.firstname + ' ' + this.lastname }
},
setterMethods : {
fullName : function(value) {
var names = value.split(' ');
this.setDataValue('firstname', names.slice(0, -1).join(' '));
this.setDataValue('lastname', names.slice(-1).join(' '));
},
}
});
Hope it helps.
AttendantUser.usernameInUse = function (username, callback) {
...
};
return AttendantUser;

Populate not working for an array of ObjectIDs

This is the implementation of my models :
var itemSchema = new Schema({
name : String,
qte : Number
});
var Item = mongoose.model('Item', itemSchema);
var orderSchema = new Schema({
state : {
type: String,
enum: ['created', 'validated', 'closed', 'starter', 'meal', 'dessert'],
required : true
},
table : {
number : {
type : Number,
required : true
},
name : {
type : String,
required : false
}
},
date: { type: Date, default: Date.now },
_items : [{type:Schema.Types.ObjectId, ref:'Item'}]
});
And this is how I do my query
getByIdRaw : function (orderId, callback) {
Order.findById(orderId)
.populate('_items')
.exec(function(err, order) {
debug(order);
callback(order);
});
}
This is my response without populating
{
_id: "5549e17c1cde3a4308ed70d5"
state: "created"
_items: [1]
0: "5549e1851cde3a4308ed70d6"
-
date: "2015-05-06T09:40:12.721Z"
table: {
number: 1
}-
__v: 1
}
...and my response when populating _items
{
_id: "5549e17c1cde3a4308ed70d5"
state: "created"
__v: 1
_items: [0]
date: "2015-05-06T09:40:12.721Z"
table: {
number: 1
}-
}
Why the _items array is empty ? What am I doing wrong ?
EDIT : the addItem function
addItem : function (orderId, item, callback) {
Order.findById(orderId)
.exec(function(err, order) {
if (err) {
error(err);
return callback(err);
}
if (order === null) {
return callback("No order with this id");
}
var newItem = new Item({
name : item.name,
qte :item.qte
});
order._items.push(newItem);
order.markModified('_items');
order.save();
callback();
});
}
The issue is the new item is never persisted to the items collection. Mongoose references only populate they don't persist a new item to the referenced collection.
addItem: function(orderId, item, callback) {
var newItem = new Item({
name: item.name,
qte: item.qte
});
newItem.save(function(err, savedItem) {
if (err) {
error(err);
return callback(err);
}
Order.findById(orderId).exec(function(err, order) {
if (err) {
error(err);
return callback(err);
}
if (order === null) {
return callback("No order with this id");
}
order._items.push(savedItem);
order.markModified('_items');
order.save(callback);
});
});
}

Categories

Resources