I want to update the plateNumber in my table car.
I used this for a specific ID:
car.update({_id:'436' }, {$set: {plateNumber: 'DG-884-AQ'}}, {multi: true},cb);
But It didn't work, and I got
ReferenceError: cb is not defined
What should I do?
and I use car as instance or Car as the model.
Thanks.
You need to provide a function:
car.update(
{_id:'436' },
{$set: {plateNumber: 'DG-884-AQ'}},
{multi: true},
(err, data) => {
if (err) {
// handle error
} else {
// handle success
}
}
);
Your code would work if you had the cb function defined with:
let cb = (err, data) => {
if (err) {
// handle error
} else {
// handle success
}
};
or:
function cb(err, data) {
if (err) {
// handle error
} else {
// handle success
}
}
but you cannot pass cb as an argument if you don't have it defined.
cb is suppose to be a function(callback)
car.update(
{_id:'436' },
{$set: {plateNumber: 'DG-884-AQ'}},
{multi: true}, function(err, resp) {
});
Related
I have a PUT request that I'm trying to have hit the backend, but for some reason, it never reaches it. What's odd is the if(req.body.bidderId){} hits no problem, but not the if(req.body.watchingGroup){}
The watching angular service uses identical code to the bidderId so I don't know what's different between the two where only one would reach the endpoint? Whats wrong with the addToWatchList call? I did testing and both console.log statements in code block return the correct value. So the data is ready to be passes, but is never received.
console.log("MADE IT TO LISTINGS BACKEND");
never outputs for watchingGroup scenario
watching.service.ts
addToWatchList(id: string, watchingGroup: string[]) {
const watching: Watching = {
id: id,
watchingGroup: watchingGroup
};
console.log("Here are the values being passed to backend");
console.log(watching.id);
console.log(watching.watchingGroup);
console.log(watching);
return this.http.put(`http://localhost:3000/api/listings/${watching.id}`, watching,
);
}
app.js
app.put("/api/listings/:id", (req, res) => {
console.log("MADE IT TO LISTINGS BACKEND");
if (req.body.biddingGroup) {
console.log("bidding has been received");
Post.findByIdAndUpdate(
{ _id: req.params.id },
{
currentBid: req.body.currentBid,
lastBidTimeStamp: Date.now(),
bidderId: req.body.bidderId,
auctionEndDateTime: req.body.auctionEndDateTime,
biddingGroup: req.body.biddingGroup,
lastBidTimeStamp: req.body.lastBidTimeStamp
},
function(err, docs) {
if (err) res.json(err);
else {
console.log(docs);
}
}
);
}
if (req.body.watchingGroup) {
console.log("watching has been received");
Post.findByIdAndUpdate(
{ _id: req.params.id },
{
watchingGroup: req.body.watchingGroup
},
function(err, docs) {
if (err) res.json(err);
else {
console.log(docs);
}
}
);
}
});
addToWatchList
addToWatchList(
auctionId: string,
watchingGroup: string[]
) {
this.watchItStatus = true;
this.userId = localStorage.getItem("userId: ");
var unique = watchingGroup.filter(function(elem, index, self) {
return index === self.indexOf(elem);
});
this.uniqueResult = unique;
watchingGroup.push(this.userId);
this.watchListService.addToWatchList(auctionId, this.uniqueResult);
}
As i suspected you're not subscribing to it. It's weird but you need to subscribe to it.
this.watchListService.addToWatchList(auctionId, this.uniqueResult).subscribe(
(res) => {
// Handle success response
console.log("SUCCESS");
},
(err) => {
// Handle error response
console.log("ERROR");
}
);
Hi I have a problem running a loop and getting the return data using Promises.
I have a getStudentMarks method for getting students marks from the database in subject wise.
getStudentMarks: function(studentId, studentStandard) {
console.log("getStudentMarks invoked...");
return new Promise(function(resolve, reject) {
r.table('student_subjects').filter({
"studentId": studentId,
"studentStandard": studentStandard
}).pluck("subjectId", "subjectName").run(connection, function(err, cursor) {
if (err) {
throw err;
reject(err);
} else {
cursor.toArray(function(err, result) {
if (err) {
throw err
} else {
console.log(result.length);
if (result.length > 0) {
studentSubjectArray = result;
var studentMarksSubjectWiseArray = [];
studentSubjectArray.forEach(function(elementPhoto) {
r.table('student_marks').filter({
"studentId": studentId,
"subjectId": studentSubjectArray.subjectId
}).run(connection, function(err, cursor) {
if (err) {
throw err;
reject(err);
} else {
cursor.toArray(function(err, result_marks) {
var studnetMarksDataObject = {
subjectId: studentSubjectArray.subjectId,
subjectName: studentSubjectArray.subjectName,
marks: result.marks
};
studentMarksSubjectWiseArray.push(studnetMarksDataObject);
});
}
});
});
resolve(studentMarksSubjectWiseArray);
}
}
});
}
});
});
}
I'm invoking the method by,
app.post('/getStudentMarks', function(req, reqs) {
ubm.getStudentMarks(req.body.studentId, req.body.studentStandard)
.then((data) => {
console.log('return data: ' + data);
})
.catch((err) => {
console.log(err);
});
});
When I run the code its working absolutely fine there is no error. I get all the student marks object in the studentMarksSubjectWiseArray array. But the problem is even before the studentSubjectArray loops gets completed, the resolve is getting executed and I'm getting a blank array as return. How do I solve the problem. I understand that I'm not doing the Promises right. I'm new to Promises so I'm not being able to figure out the right way.
That happens because inside your studentSubjectArray.forEach statement you perform set of asynchronous operations r.table(...).filter(...).run() and you push their result into the array. However, those actions finish after you perform the resolve(), so the studentMarksSubjectWiseArray is still empty. In this case you would have to use Promise.all() method.
let promisesArray = [];
studentSubjectArray.forEach((elementPhoto) => {
let singlePromise = new Promise((resolve, reject) => {
// here perform asynchronous operation and do the resolve with single result like r.table(...).filter(...).run()
// in the end you would perform resolve(studentMarksDataObject)
r.table('student_marks').filter({
"studentId": studentId,
"subjectId": studentSubjectArray.subjectId
}).run(connection, function(err, cursor) {
if (err) {
throw err;
reject(err);
} else {
cursor.toArray(function(err, result_marks) {
var studnetMarksDataObject = {
subjectId: studentSubjectArray.subjectId,
subjectName: studentSubjectArray.subjectName,
marks: result.marks
};
resolve(studnetMarksDataObject);
});
}
});
});
promisesArray.push(singlePromise)
});
Promise.all(promisesArray).then((result) => {
// here the result would be an array of results from previously performed set of asynchronous operations
});
I'm trying to setup (this is my first attempt) a function that receives input, passes it through a function, then the results of that through a follow up.
I'm getting the following error
TypeError: Cannot read property 'exec' of undefined
I've never used Promises before and I believe that's what I should be doing in this instance, I don't think I'm quite understanding how to structure things with the .exec and .then parts.
app.get('/api/gameobjects/:userid/:golng/:golat/:dist', (req, res) =>
{
console.log("First part");
GameObject.getNearGameObjects(req.params.golng, req.params.golat, req.params.dist)
.exec((err, gameobject) =>
{
if (err)
{
res.json(err);
}
})
.then((gameobject) =>
{
console.log("Third part");
User.addGameObjectToUser(req.params.userid, gameobject)
})
});
EDIT:
Code for the getNearGameObjects:
// Get Near Game Objects
module.exports.getNearGameObjects = function( long, lat, dist, callback, limit )
{
var coords = [];
coords[ 0 ] = long;
coords[ 1 ] = lat;
var query =
{ geometry: { $near: { "$geometry": { "type": "Point", "coordinates": [long, lat] }, $maxDistance: dist } } };
GameObject.find( query, callback ).limit( limit );
};
Code for the addGameObjectToUser
// Add object to user
module.exports.addGameObjectToUser = function(id, gameobject, callback)
{
var query = { _id: id };
User.findByIdAndUpdate( query, { "$addToSet" : { "inventory" : gameobject } } );
};
If you don't return anything from the function, by default it returns undefined
You're getting
TypeError: Cannot read property 'exec' of undefined
because .exec() will be called on the returned undefined.
If you want to call .exec() on the find(), you should remove callback parameter on it. So that it returns promise
Making those changes,
module.exports.getNearGameObjects = function (long, lat, dist, callback, limit) {
return GameObject.find({
geometry: {
$near: {
"$geometry": {
"type": "Point",
"coordinates": [long, lat]
},
$maxDistance: dist
}
}
}).limit(limit);
};
Similarly, .catch() will handle error when it occurs.
GameObject.getNearGameObjects(req.params.golng, req.params.golat, req.params.dist)
.exec().then((gameobject) => {
console.log('Third part');
return User.addGameObjectToUser(req.params.userid, gameobject);
}).catch((err) => {
res.json(err);
});
I decided to go back to the code I know and nested by called based on result, this means more code, but more importantly it works.
I'd still be very interested in understanding how to do promise based code in the API, as it does look like it would be a tidier format to work with.
Here's the working code:
app.get('/api/gameobjects/:userid/:golng/:golat/:dist', function (req, res)
{
console.log("starting");
GameObject.getNearGameObject(req.params.golng, req.params.golat, req.params.dist, function (err, gameobject)
{
if (err)
{
res.json(err);
}
console.log("got a game object");
User.addGameObjectToUser(req.params.userid, gameobject, function (err, user)
{
if (err)
{
res.json(err);
}
console.log("updated a user");
GameObject.removeGameObjectByLocation(req.params.golng, req.params.golat, function(err, gameobject)
{
if (err)
{
res.json(err);
}
console.log("removed a game object");
res.json(gameobject);
});
});
});
});
exports.getCityCascade = function (req, res) {
var result = {};
Province.find().exec(function (err, provinces) {
result.provinces = provinces;
var provinceCount = 0;
async.whilst(
function () {
return provinceCount < provinces.length
}
, function (callback) {
City.find({province: provinces[provinceCount].id}).exec(function (err, cities) {
if (err) {
callback(err);
} else {
result.provinces[provinceCount].cities =cities;
}
provinceCount++;
callback(null , result);
});
}, function (err, result) {
if (err) return res.jsonp({message: err.message});
return res.jsonp({
status: '200',
results: result});
}
)
})
}
When I add the cities field to provinces, It seems doesn't work. the response body doesn't contain the filed cities. How to fix it? Any advice would be very helpful.
The problem is just a conflict between variable names: you declared a var result outside Province.find(), but the async.whilst() also uses result as the second argument of its callback function. Just rename one of them and it should work.
I have an array of documents with unique _id and I want to insert them to my database. Some of them already in db, and for those I want to update an array property (push in array an item). All of this I need to make asyncronuosly, so after all inserted/updated I want to write response back (with callback) to client than all ok or write an error. After googling on subject I've found this solution with async module I've tried to implement it for my case. Now my code looks like this:
function processUsers(arr, listName, callback) {
var users = global.db.collection('vkusers');
var q = async.queue(function(task, cb) {
console.log('upsert butch');
users.insert(task.doc, function(err, doc) {
if (err) {
users.update({
_id : task.doc._id
}, {
$addToSet : {
mLists : listName
}
}, function(error, result){ console.log(error); console.log(result); });
}
});
}, arr.length);
for ( var doc in arr) {
q.push({
doc : arr[doc]
}, function(err) {
if (err)
callback(err, null);
})
}
q.drain = function() {
// this is the queue's callback, called when the queue is empty,
// i.e. when all your documents have been processed.
console.log('drain');
callback(null, { result: "success", upserted: arr.length });
}
}
Callback has signature callback(error, result), arr - my array of documents. I've tested it and with database everything is OK, i am getting the right result. But callback, and q.drain never fired!
You need to call async.queue's callback (cb in your code) when your insert/update is complete. Something like this:
var q = async.queue(function(task, cb) {
console.log('upsert butch');
users.insert(task.doc, function(err, doc) {
if (err) {
users.update({
_id : task.doc._id
}, {
$addToSet : {
mLists : listName
}
}, function(error, result) {
console.log(error);
console.log(result);
cb(error); // Update finished; call cb and pass in "error" so that it can bubble up if it exists
});
} else {
cb(); // Insert succeeded; call cb
}
});
}, arr.length);