I've created a watson rank and retrieve collection. I was able to add a document and I can search it, but it was a test document. How do I delete it?
This is what I want to delete:
// add a document
var doc = { id : 1234, title_t : 'Hello', text_field_s: 'some text' };
solrClient.add(doc, function(err) {
if(err) {
console.log('Error indexing document: ' + err);
} else {
console.log('Indexed a document.');
solrClient.commit(function(err) {
if(err) {
console.log('Error committing change: ' + err);
} else {
console.log('Successfully commited changes.');
}
});
}
});
solrClient.deleteByID(1234, function(err) {
solrClient.commit(function (err) {
// obviously add error-handling
});
});
Related
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});
}
]);
}
});
});
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);
});
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);
}
}
I have a weird conflict with my pouchDB code trying to update a document in my database
code:
this.addToExistingUser = function (docId, key, value) {
usersDatabaseRemote
.get(docId)
.then(function (doc) {
doc[key] = value;
return usersDatabaseRemote.put(doc, docId, doc._rev);
})
.then(function () {
console.log('added field: ' + key + ' to doc ' + docId);
})
.catch(function (err) {
console.log("error from addToExistingUser:");
console.log(JSON.stringify(err));
});
}
where :
.factory('usersDatabaseRemote', [
'pouchDB',
function (pouchDB) {
'use strict';
var usersDatabaseRemote = pouchDB('https://id:pwd#id.cloudant.com/boardl_users');
return usersDatabaseRemote;
}
])
leads to :
{"status":409,"name":"conflict","message":"Document update conflict","error":true,"reason":"Document update conflict."}
But as you can see from the code I take the revision number rev from the remote document so I don't see why is there a problem with this.
Thanks
credit: #AlexisCôté
I was calling several times the async function that updates the remote doc
pouchDBservice.addToExistingUser(userr._id, 'weight',
pouchDBservice.addToExistingUser(userr._id, 'height', userHeight);
pouchDBservice.addToExistingUser(userr._id, 'technique', userTechnique);
and this was messing with the ._rev number.
So now I am doing all the parameters at the same time in an object :
pouchDBservice.addObjectToExistingUser(userr._id, objectToAdd);
with :
this.addObjectToExistingUser = function (docId, obj) {
usersDatabaseRemote
.get(docId)
.then(function (doc) {
for (var key in obj) {
if (!obj.hasOwnProperty(key)) continue;
console.log(key, obj[key])
doc[key] = obj[key];
}
return usersDatabaseRemote.put(doc);
})
.then(function () {
console.log('addObjectToExistingUser added object: ' + JSON.stringify(obj) + ' to doc ' + docId);
})
.catch(function (err) {
console.log("error from addObjectToExistingUser:");
console.log(JSON.stringify(err));
});
};
Im creating a comments system and im trying to add values to the view such as the text, userName, timePosted and userProfileImageURL but the only one that wont appear is the userProfileImageURL.
I think the problem is with the controller function but it could be somewhere else altogether.
/**
* Comment middleware
*/
exports.commentByID = function (req, res, next, id) {
Comment.findById(id).populate('user', 'displayName').exec(function (err, comment) {
if (err) return next(err);
if (!comment) return next(new Error('Failed to load Comment ' + id));
req.comment = comment;
next();
});
};
or Here Possibly
/**
* List of Comments
*/
exports.list = function (req, res) {
var id = req.dealId;
console.log('Log - ' + id);
Comment.find( )
.sort('-created')
.populate('user', 'displayName')
.exec(function (err, comments) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.jsonp(comments);
}
});
};
What does the 'user' and 'displayName' parameter in this function do?
Can i add the 'userProfileImageURL' also to the returned data somehow?
Im using the profileImageURL value like this. display name is showing but not the profileImageURL
<img ng-src="{{post.user.profileImageURL}}" alt="{{post.user.displayName}}" />
/**
* List of Comments
*/
exports.list = function (req, res) {
var id = req.dealId;
console.log('Log - ' + id);
Comment.find( )
.sort('-created')
.populate('user')
.exec(function (err, comments) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.jsonp(comments);
}
});
};
Just have to delete the displayName parameter and it will send the whole user object.