Mongoose schema/methods disappearing when overwriting subdocument - javascript

I have a schema with a method - 2 variations. They both work fine when adding an address the firs time but version one will blow up when adding another address (i.e. when it goes through the for loop). What I mean by blowing up is that it seems to destroy my order instance - there is no more 'save' method.
The schema
var Address = new Schema({
type: { type: String, enum: ['shipping', 'billing'] },
street: { type: String, required: true },
city: { type: String, required: true },
region: String,
country: String,
postal: { type: String, required: true },
});
var Order = new Schema({
email: {
type: String
},
address: [Address]
});
Now if I have added an addAddress() method to my schema. Here are the 2 versions I have tried.
// Version 1 - has issues on subsequent call
Order.methods.addAddress = function() {
var data = { type: 'shipping', city: 'Tempe', postal: '85281', street: '420 Mill Ave'};
for(var i = this.address.length-1; i >=0; i--) {
if(this.address[i].type === type) {
delete address[i];
}
}
this.address.push(data);
}
// Version 2 - works fine
Order.methods.addAddress = function() {
var data = { type: 'shipping', city: 'Tempe', postal: '85281', street: '420 Mill Ave'};
var found = false;
for(var i = this.address.length-1; i >=0; i--) {
if(this.address[i].type === type) {
found = true;
this.address[i] = data;
}
}
if(!found)
this.address.push(data);
}
Trying to save after using V1 that will yield this error:
Uncaught Exception
TypeError: Object #<Object> has no method 'save'
at /var/node_modules/mongoose/lib/document.js:1270:13
at Array.forEach (native)
at model.pre.err.stack (/var/node_modules/mongoose/lib/document.js:1252:12)
at model._next (/var/node_modules/mongoose/node_modules/hooks/hooks.js:50:30)
at model.proto.(anonymous function) [as save] (/var/node_modules/mongoose/node_modules/hooks/hooks.js:96:20)
at Promise.<anonymous> (/var/controllers/cart.js:79:11)
at Promise.<anonymous> (/var/node_modules/mongoose/node_modules/mpromise/lib/promise.js:171:8)
at Promise.EventEmitter.emit (events.js:95:17)
at Promise.emit (/var/node_modules/mongoose/node_modules/mpromise/lib/promise.js:88:38)
at Promise.fulfill (/var/node_modules/mongoose/node_modules/mpromise/lib/promise.js:101:20)
Let's take the following code:
Order.findById(id.exec(function(err, o) {
o.addAddress('shipping', { street: '1000 Mill Ave', city: 'Tempe', postal: '85281' });
console.log(o);
o.save(function(err, order) {
});
})
Notice the console call? On each variation it appear that the order object is ok:
{
_id: 007d0000b10000000000000c,
address: [{
street: '420 Mill Ave',
postal: '85281',
city: 'Tempe',
type: 'shipping'
_id: 52b2459f1547a5e12300000b
}]
}
But it seems to have lost something such as the 'save' method.
Any ideas?

You're defining the address as a dict and not as an address object. Instead you should do something like this:
Order.methods.addAddress = function(type, data, next) {
// Have your removal code here
var self = this
var address = new Address(data)
address.save(function(err, address) {
if (err) {
...
} else {
self.address.push(address)
next()
}
})
}
Notice that I'm populating the address array with an address object as per the schema definition.

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.

model.find({}).populate('place').populate('location') does not return place and location

I have document with the following structure on MongoDb,
I am using Mongoose version ^4.8.1 with my node application. I have created 3 schema models for the above document which are as follows,
Event.js
var mongoose = require('mongoose');
var eventSchema = new mongoose.Schema({
description: {
type: String
},
end_time: {
type: Date
},
start_time: {
type: Date
},
name: {
type: String
},
place: {
type: mongoose.Schema.Types.ObjectId,
ref: 'place'
}
});
eventSchema.index({name: 'text'},{'place.location.country':"text"});
var Event = mongoose.model('events', eventSchema);
module.exports= Event;
Place.js
var mongoose = require('mongoose');
var placeSchema = new mongoose.Schema({
name: {
type: String
},
location: {
type: mongoose.Schema.Types.ObjectId,
ref: 'location'
}
});
var Place = mongoose.model('place', placeSchema);
module.exports= Place;
Location.js
var mongoose = require('mongoose');
var locationSchema = new mongoose.Schema({
city: {
type: String
},
latitude: {
type: String
},
country: {
type: String
},
located_in: {
type: String
},
state: {
type: String
},
street: {
type: String
},
zip: {
type: String
},
});
var Location = mongoose.model('location', locationSchema);
module.exports= Location;
Common handler to access /query database,
dbHandler.js
querandpoplulate : function(model,condition,options)
{
return new Promise(function(resolve, reject) {
options = options||{};
console.log("model is" + model);
model.find({}).populate('place').populate('location').exec(function(error, data) {
if (error)
console.log(error);
reject(error);
console.log(data);
resolve(data);
})
})
}
Here is how i query,
dbHelper.querandpoplulate(mongoose.model('events'), {$text: {$search: searchString},'place.location.country': countryString},function(error,data){
callback(data);
});
Question: it does not return the result set with the place and location , it returns null in place field.
It looks to me like your documents are saved as embedded documents, but not as referenced documents.
To fetch such documents, you don't need to do any population. Simple find query should work for you.
Try this:
model.find({}).exec(function(error, data) {
if (error)
console.log(error);
reject(error);
console.log(data);
resolve(data);
})
As you are not saving the data in the mongoDB but only retrieving it. you need to define the schema that matches with the document structure.
As discussed with you, i think you need to change the Schema, and combine all 3 schemas in one file (Event.js).
var mongoose = require('mongoose');
var locationSchema = new mongoose.Schema({
city: {
type: String
},
//add other fields here
});
var placeSchema = new mongoose.Schema({
name: {
type: String
},
location: locationSchema
});
var eventSchema = new mongoose.Schema({
description: {
type: String
},
//add other fields here too
place: placeSchema
});
eventSchema.index({name: 'text'},{'place.location.country':"text"});
var Event = mongoose.model('events', eventSchema);
module.exports= Event;

Error Cannot set property of undefined

Hi I have this code in Node.Js, in this I realize a find query with mongoose
router.post('/query',function(req,res,next){
if (req.body){
var result=[];
console.log(req.body.filters);
Pollee.find(req.body.filters)
.select('id age birthday user')
.populate('user','email')
.lean(true)
.exec(function(err,pollees){
if(err) {
console.log(err);
return next(err);
}
for (var i = 0; i < pollees.length; i++){
var query = test(pollees[i]._id);
query.exec(function(err,inters){
if(err)
return console.log(err);
inters.forEach(function(inter){
pollees[i].interaction = inter;
});
});
}
res.json(pollees);
};
})
}
});
function test(id){
var promise = Interaction.find({pollee:id}).select('status other');
return promise;
}
My problem here its in the Interaction.find when I try to pass the results of this query on pollees[i].interaction = inter; the console set me error
Cannot set property pollees[i].interaction = inter; of undefined
Any idea?
The models I used
var interactionSchema = new Schema({
pollee: { type: ObjectId, ref: 'Pollee' },
answers: { type: [ObjectId], ref: 'Answer', autopopulate: true },
status: type: String
});
var PolleeSchema = new Schema({
firstName: String,
lastName: String,
gender: String,
user: { type: ObjectId, ref: 'User', required: true },
interactions: { type: [ObjectId], ref: 'Interaction', autopopulate: true }
});
var userSchema = new Schema({
email: String,
pollee: { type: Schema.Types.ObjectId, ref: 'Pollee', autopopulate: true }
});
Thanks a lot!
I'd say the problem the following: in the for cycle of your code you're calling async method query.exec(). By the time it executes it's callback, for cycle has already finished and value of i === pollees.length. Thus pollees[i] is pointing to non-existent array element (undefined) and you get an error "cannot set property of undefined" when your trying to set it's property interaction.
One of the ways to fix this would be to use .bind:
query.exec(function(i, err,inters){ //i is among the params in your callback
if(err)
return console.log(err);
inters.forEach(function(inter){
pollees[i].interaction = inter;
});
}.bind(null, i)); //you're binding the variable 'i' to the callback
EDIT:
And in order for res.json(pollees); to work (which is a different problem) you should wrap all your callbacks in a Promise. It should probably look like something like this:
var queries = []; //an array of promises
for (var i = 0; i < pollees.length; i++){
queries.push(test(pollees[i]._id)); //add a promise to the array
}
//wait for all promises to resolve
Promise.all(queries).then(function(results) {
results.forEach(function(inter, index){
pollees[index].interaction = inter;
});
res.json(pollees); //return response
});

Categories

Resources