How to clear an array in MongoDB - angularjs

I have an emails object that contains an array in a mongodb database. However, when I try to use $set to make the array empty it doesn't work. How am I supposed to clear the array?
exports.clearEmails = function(req, res, next) {
var listId = req.params.id;
var errors = req.validationErrors();
if (errors) {
return res.status(400).send(errors);
}
EmailList.update({'_id': listId}, {$set: {'emails': []}}, function(err,results) {
if (err) {
return res.status(400).send(err);
} else {
return res.status(200).send(results);
}
});
}

Related

How to create array of objects from http.get

I have http.get and it's impossible for me to create array of objects. Can you help me ? I need to create loop on array of returned objects and i can't do this.
export class Link {
idStat: String;
idAccount: String;
}
links: Link [];
router.get('/linkGetAll', function(req, res, next) {
Link.find(function (err, products) {
if (err) return next(err);
res.json(products);
});
});
getAllLinks(){
return this.http.get('/main/linkGetAll');
}
this.api.getAllLinks().subscribe((data) => {
this.links = data;
})
for(let item in this.links)
{
DOESN'T WORK
}
getAllLinks(){
return this.http.get('/main/linkGetAll')
.pipe(map(res => {
// do something here
// res.forEach() or res.map()
return 'it';
})
);
}
Before going to
for(let item in this.links)
{
DOESN'T WORK
}
Ensure that this.links has data in it.(use async/await along with toPromise())
Please read this section about HTTP of the Angular tutorial and the Angular API.
The get method accepts a type:
get<T>(...): Observable<T>
so you could modify your implementation of getAllLinks:
getAllLinks(): Observable<Link[] {
return this.http.get<Link[]>('/main/linkGetAll');
}
Now you should should be able to iterate the response:
getAllLinks().subscribe(links => {
links.forEach(link => // do what you need);
}

Can't compare MongoDB data with javascript array

I want to compare the data which I got from Mongo to javascript array. I am using lodash to compare. But it always return incorrect result.
var editUser = function(userData, getOutFunction) {
var status = CONSTANTS.NG;
checkExistUser(userData._id).then(function(user) {
if (user !== null) {
var userGroup = JSON.stringify(user.group);
user.group = user.group.map((groupId) => {
return groupId.toString();
});
var removedGroups = _.difference(userGroup, userData.group);
var addedGroups = _.difference(userData.group, userGroup);
console.log('Removed Groups: ', removedGroups);
console.log('Added Groups: ', addedGroups);
} else {
status = CONSTANTS.NG;
logger.debug(DEBUG_CLASS_NAME, "Cannot find object");
if (typeof(getOutFunction) !== 'undefined') {
getOutFunction(status, null);
} else {
NO_CALLBACK();
}
}
}).catch(function() {
console.log('Promise is error');
});
var checkExistUser = function(userId) {
return new Promise(function(resolve, reject) {
UserDAO.findById(userId, function(err, user) {
if (err) {
logger.debug(DEBUG_CLASS_NAME, {
name: err.name,
code: err.code,
message: err.message,
method: "checkExist"
});
resolve(null);
} else {
resolve(user);
}
});
});
}
For example:When I try to input value for lodash difference function
var user.group = ["58b8da67d585113517fed34e","58b8da6ed585113517fed34f"];
var userData.group = [ '58b8da67d585113517fed34e' ];
I want lodash difference return below result:
Removed Groups: ['58b8da6ed585113517fed34f']
Added Groups: []
However, the function gave me the result like:
Removed Groups: []
Added Groups: [ '58b8da67d585113517fed34e' ]
Can anyone help me in this case?
I will do appreciate it.
I have had this issue as well, the result from mongodb is an ObjectId type so you can compare the someObjectId.toString() value with your array of strings, or you could use
someObjectId.equals(stringOrObjectIdValue)
However, if you want to keep using lodash functions you will either have to force both arrays to strings or to ObjectIds before passing them into the function.

Set json array in nodejs async

I am new in nodejs and I want to make a json array by comparing id inside a loop but the MongoDB function does not wait for the loop to complete, so data is not coming out properly. It displays the data before the loop ends, below is the code:
router.get('/getallcountrydataup',function(req, res) {
Country
.where('isDeleted').equals(false)
.exec(function(err,cData){
if (!cData) {
res.json({'status':0,'message': 'No data found','data':[]});
} else{
async.waterfall([
function (done) {
var countryalldata = [];
for (var i = 0; i < cData.length; i++) {
var country_s = cData[i];
State.where('s_c_id').equals(country_s._id)
.exec(function(err, statedata){
country_s.statecount = statedata.length;
//console.log(country_s._id);
console.log(country_s.statecount);
});
countryalldata.push(country_s);
}
done(err, countryalldata);
// console.log(countryalldata);
},
function (countryalldata, done) {
console.log(countryalldata);
res.json({
'status': 1,
'message': 'Data found',
'data': countryalldata
});
}
]);
}
});
});
Here is output of the countryalldata variable printed before the loop will complete. I want to print its output after loop execution is complete.
State.where is asynchronous so it should be synchronized. For example with async.map
router.get('/getallcountrydataup',function(req, res) {
Country
.where('isDeleted').equals(false)
.exec(function(err,cData){
if (!cData) {
res.json({'status':0,'message': 'No data found','data':[]});
} else {
async.waterfall([
function (done) {
async.map(cData, function (country_s, done2) {
// Convert country_s into plain object. It's not a mongoose
// model anymore
country_s = country_s.toObject();
State.where('s_c_id')
.equals(country_s._id)
.exec(function(err,statedata){
if (err) {
done2(err);
return;
}
country_s.statecount = statedata.length;
console.log(country_s.statecount);
done2(null, country_s)
});
}, function(err, countryalldata) {
if (err) {
done(err);
}
else {
done(null, countryalldata)
}
});
},
function (countryalldata, done) {
console.log(countryalldata);
res.json({'status':1,'message': 'Data found','data':countryalldata});
}
]);
}
});
});

CloudantDB & NodeJS: Query data with specific id

I just created a NodeJS cloudantDB web starter on bluemix. Then, I have a API get data from cloudantDB and get successfull but it returns all data. Please see js file:
js file:
app.get('/api/provider', function(request, response) {
console.log("Get method invoked.. ")
db = cloudant.use(dbCredentials.dbProvider);
var docList = [];
var i = 0;
db.list(function(err, body) {
if (!err) {
var len = body.rows.length;
console.log('total # of docs -> '+len);
if(len == 0) {
// error
} else {
body.rows.forEach(function(document) {
db.get(document.id, { revs_info: true }, function(err, doc) {
if (!err) {
if(doc['_attachments']) {
// todo
} else {
var responseData = createResponseDataProvider(
doc._id,
doc.provider_type,
doc.name,
doc.phone,
doc.mobile,
doc.email,
doc.logo,
doc.address
);
}
docList.push(responseData);
i++;
if(i >= len) {
response.write(JSON.stringify(docList));
console.log('ending response...');
response.end();
}
} else {
console.log(err);
}
});
});
}
} else {
console.log(err);
}
});
If I want to add parameter to API to get specific data from DB , Do we need create search index or query on cloudant, afer that call API the same : app.get('/api/provider/:id'). Please help me review and sharing. Thanks
you could get the document by id/name:
db.get(docID, function(err, data) {
// do something
});
references:
https://github.com/apache/couchdb-nano#document-functions
https://github.com/cloudant/nodejs-cloudant#api-reference
You can use a search function of Cloudant.
You need to create search index. In search index you can manage what data you want to get.
Example: https://cloudant.com/for-developers/search/
Following this code after create search index.
...
var query = {q: "id:doc.id"};
db.search('design document name', 'index name', query, function(er, result) {
if (er) {
throw er;
}
console.log(result);
});

array schema store empty values

I want store values in mongodb using node controller but it will store an empty array inside mongodb
1).This is node controller using to accept the req parameter
this.childQuestionId = function(req, res, next){
try{
var userObj = {
'child.quiz.questionId' : req.params.questionId,
'child.quiz.score' : req.params.score,
//'child.quiz.time' : req.params.time
'child.quiz.time' : new Date().toISOString()
};
var childupdate = new childQuiz(userObj);
childupdate.save(function(err,data){
if(err) return next(err);
console.log("Data saved successfully");
res.send(data);
});
}catch(err){
console.log('Error While Saving the result ' +err);
return next(err);
}
}
2).This is mongodb schema using to store the value. Here i am using array quiz schema to store values is array
child:{
quiz:[
{
/*questionId:{
type: mongoose.Schema.Types.ObjectId,
ref: 'commonquestions'
},*/
questionId:{type:String},
score:{type:Number},
time:{type:String}
}
]
}
3).This is my json result sending values using postman
{
"__v": 0,
"_id": "57a43ec68d90b13a7b84c58f",
"child": {
"quiz": []
}
}
MongoDB save() function accepts 2 parameters, document and data, but in your code, you use a callback function. Should you check it out?
https://docs.mongodb.com/manual/reference/method/db.collection.save/#db.collection.save
Try with this code in your controller
this.childQuestionId = function(req, res, next){
try{
var userObj = {
'questionId' : req.params.questionId,
'score' : req.params.score,
//'time' : req.params.time
'time' : new Date().toISOString()
};
var childupdate = new childQuiz();
childupdate.quiz.push(userObj);
childupdate.save(function(err){
if(err) return next(err);
console.log("Data saved successfully");
res.send(childupdate);
});
}catch(err){
console.log('Error While Saving the result ' +err);
return next(err);
}
}

Resources