Unable to retrieve value from PouchDB - couchdb

After inserting data using PouchDB I tried db.getAll() to retrieve all the documents and db.get() for single documents but none of the objects returned contained the value I was inserted in.
What am I doing wrong?
new Pouch('idb://test', function(err, db) {
doc = {
test : 'foo',
value : 'bar'
}
db.post(doc, function(err, data) {
if (err) console.error(err)
else console.log(data)
})
db.allDocs(function(err, data) {
if (err) console.error(err)
else console.log(data)
})
})

Your allDocs query is running before you have completed inserting the data into PouchDB, due to the IndexedDB API all database queries are asynchronous (they likely would have to be anyway as it's also a HTTP client).
new Pouch('idb://test', function(err, db) {
var doc = {
test : 'foo',
value : 'bar'
};
db.post(doc, function(err, data){
if (err) {
return console.error(err);
}
db.allDocs(function(err, data){
if (err) console.err(err)
else console.log(data)
});
});
});
... should work.

Related

Mongoose.updateOne() not updating the value in a db

I am new to nodejs. Mongoose.updateOne is not saving value into db. when i run this, it prints image uploaded in a console but it's not reflecting in a mongodb. I want to update my photo in a db
var a = new photo();
a.img.data = req.files.image.data
a.img.contentType = req.files.image.mimetype;
a._id = req.params.id;
Here is my updateOne method
a.updateOne({_id:req.params.id}, function (err, result) {
if (err){
console.log(err)
}else{
res.send({ status: 1 })
console.log("image uploaded"+result)
}
});
Update: I failed to pass update syntax, and instead of using modelname (photo) i used variable name 'a'. Here it works
photo.updateOne({_id:req.params.id},{img:{data:req.files.image.data,contentType:req.files.image.mimetype}},function (err, result) {
if (err){
console.log(err)
}else{
res.send({ status: 1 })
console.log("image uploaded"+result)
}
});

Finish execution if first query returns a value Node.js Express.js mongoDB

Before starting, please mind that i have been searching this over 2+ hours, the answer will be simple i know but i couldnt get it to work . i am new to express node mongodb,
MongoClient.connect(url, function(err, db) {
if (err) {
res.status(err.status); // or use err.statusCode instead
res.send(err.message);
}
var usernameGiven = req.body.usernameGiven;
//Select the database
var dbo = db.db("notifellow");
//run the query
var query = { username: usernameGiven , friends: []};
dbo.collection("users").findOne({ username: usernameGiven}, function(err, result) {
if (err){
res.status(err.status); // or use err.statusCode instead
res.send(err.message);
console.log("Query Error Occured!");
}
else {
if (result) {
//Send the response
res.send("EXISTS");
//I WOULD LIKE TO EXIT IF THIS LINE EXECUTES
}
}
});
dbo.collection("users").insertOne(query, function(err, result) {
if (err){
res.status(err.status); // or use err.statusCode instead
res.send(err.message);
console.log("Query Error Occured!");
}
else {
if (result) {
//Send the response
res.send("CREATED 201");
} else {
res.send("Failed to insert");
}
}
});
db.close();
});
my goal is to check if an user doesnt exists with given username, i would like to insert that to the DB.
i would like to exit if my query finds an match and arrange such that insertOne wont execute. please enlighten me!!
Once you are not using the async/await syntax you will have to nest the calls to MongoDB, so they execute in series. You can also use a module like async to achieve this.
MongoClient.connect(url, function(err, db) {
if (err) {
res.status(err.status); // or use err.statusCode instead
res.send(err.message);
}
var usernameGiven = req.body.usernameGiven;
//Select the database
var dbo = db.db("notifellow");
//run the query
var query = { username: usernameGiven , friends: []};
dbo.collection("users").findOne({ username: usernameGiven}, function(err, result) {
if (err){
res.status(err.status); // or use err.statusCode instead
db.close();
console.log("Query Error Occured!");
return res.send(err.message);
}
if (result) {
db.close();
return res.send("EXISTS");
}
dbo.collection("users").insertOne(query, function(err, result) {
if (err){
res.status(err.status); // or use err.statusCode instead
db.close();
console.log("Query Error Occured!");
return res.send(err.message);
}
db.close();
if (result) {
return res.send("CREATED 201");
}
res.send("Failed to insert");
});
});
});
Try this
dbo.collection("users").findOne({ username: usernameGiven}, function(err, result) {
if (err){
//put the error logic
}
else {
if (result) {
//Send the response
return result;
}
else{
// if above if block fails it means that user does not exist
//put the insert logic
}
});

Execute three operations in Mongodb or cancel if just one fails

I need to store one record in three different collections at the same time, but I need that if just one of this operations fails (for any kind of reasons) the entire procedure will be canceled. In a few words, I need to be sure that this record is stored correctly in each all the three collections: I need to avoid the situation where the record is stored in just two (or one) collections.
This is my actual code:
var insertOne = function(data) {
req.app.locals.db.collection('document_1').findOneAndUpdate({'id': data.id}, {$set: {'element': 'data.element}}, {returnOriginal: false}, function(err, result) {
if (err) {
console.log('error 1');
return;
}
if(result) insertTwo(data);
});
}
var insertTwo = function(data) {
req.app.locals.db.collection('document_2').findOneAndUpdate({'id': data.id}, {$set: {'element': 'data.element}}, {returnOriginal: false}, function(err, result) {
if (err) {
console.log('error 2');
return;
}
if(result) insertThree(data);
});
}
var insertThree = function(data) {
req.app.locals.db.collection('document_2').findOneAndUpdate({'id': data.id}, {$set: {'element': 'data.element}}, {returnOriginal: false}, function(err, result) {
if (err) {
console.log('error 3');
return;
}
if(result) console.log('success!');
});
}
insertOne(mydata);
Thanks.

Return all documents from Cloudant db through nodeJs

Passing null or an empty Json to the selector does not seem to work.
I am trying to get all the data in a database.
Tried:
db.list({}, function (err, data) {
if (err) {
return console.log("Error:",err.message);
}
console.log(data);
});
db.find(null, function (err, data) {
if (err) {
return console.log("Error:",err.message);
}
console.log(data);
});
db.bulk({docs:[]}, function (err, data) {
if (err) {
return console.log("Error:",err.message);
}
console.log(data);
});
To get a list of all the documents, don't pass anything at all e.g.
db.list(function (err, data) {
console.log(err, data);
});
If you want the document bodies too, then pass in include_docs=true:
db.list({include_docs:true}, function (err, data) {
console.log(err, data);
});
This mirrors the CouchDB API for the GET /db/_all_docs endpoint - without any parameters, you get all the document ids and revision tokens.

apply update options without save for pre-validation - mongoosejs

In any webapp i press a plus button and a value will be increased.
When i hit the button fast the validation does not work, cause the validations does not prevent (excepted behavior, the value is not out of the validations range). But the value will be setted down further, cause the rest of the reqeust will be submitted.
Important: the update options are dynamically (for instance $inc or $set).
Current Code
module.model.update({ _id: id }, options /* are dynamic */, { safe: true }, function (err, updatedDocument) {
if (err) return respond(400, err);
module.model.findOne({ _id: id }, function (err, foundDocument) {
if (err) return respond(400, err);
foundDocument.validate(function (err) {
if (err) return respond(400, err);
return respond(200, foundDocument); // callback method
});
});
});
First guess to prevent the problem
module.model.findOne({ _id: id }, function (err, foundDocument) {
foundDocument.set(options);
foundDocument.validate(function (err) {
if (err) return respond(400, err);
foundDocument.save(function (err, savedDocument) {
if (err) return respond(400, err);
return respond(200, doc);
});
});
});
...then the save just will preformed when the validation is valid.
But there is a porblem: The set method does not support $inc or other pseudo setters, or does it?
I saw the possibility to use the constructor of the update function (Show Code), but i don't know how to use it: this.constructor.update.apply(this.constructor, args);
Do you have any good practise for this problem ?
The solution was to create a customized version for $inc.
What i've done is to replace the set method of mongoosejs.
This is now extendable, but a quiet custom way to validate before an update. When someone have another solution. Post it please.
module.model.findOne({ _id: id }, function (err, foundDocument) {
for(var optionsProp in options) {
if(optionsProp === '$inc') {
for(var incProp in options[optionsProp]) {
foundDocument[incProp] += options[optionsProp][incProp];
}
}
}
foundDocument.validate(function (err) {
if (err) return respond(400, err);
foundDocument.save(function (err, savedDocument) {
if (err) return respond(400, err);
return respond(200, savedDocument);
});
});
});

Resources