Updating doc in Pouch DB - javascript

I have a DB in PouchDB, and I need to be able to update documents. So when I click "update" in the table I get the data from the fields into a form, then I want to change data in the form and press "Save Updated" button and have the fields updated. Here's what I've tried:
function saveUpdated(){
var vaucherID = window.document.VaucherForm.vaucherID.value;
var date = window.document.VaucherForm.date.value;
var invoiceNumber = window.document.VaucherForm.invoiceNumber.value;
var vendorID = window.document.VaucherForm.vendorID.value;
var amount = window.document.VaucherForm.amount.value;
var fund = window.document.VaucherForm.fund.value;
var deptID = window.document.VaucherForm.deptID.value;
var descript = window.document.VaucherForm.descript.value;
//I get idValue from when I have all values from DB get into form
db.get('idValue').then(function(doc) {
return db.put({
_id: 'idValue',
_rev: doc._rev,
vaucherID: vaucherID,
date: date,
invoiceNumber: invoiceNumber,
vendorID: vendorID,
amount: amount,
fund: fund,
deptID: deptID,
descript: descript
});
}).then(function(response) {
// handle response
}).catch(function (err) {
console.log(err);
});
}
So as I do this I get this error
o {status: 404, name: "not_found", message: "missing", error: true, reason: "missing"}

Hm, maybe it's because the doc._rev is undefined/null, so this is treated differently than just not including the _rev field at all? Do you have a live example to reproduce?

Related

Find a Pouchdb document by date

i created the db and inserted the records below is my doc
var doc = {
_id: Sno,
Date:date,
time:Time,
trip : Trip,
triptype:TripType,
vechicleNo: VechicleNo,
customer: Customer,
vechicletType: VechicleType,
};
now i want to get the values based on date selection
on selecting date i want to get all values based on date
i used the find plugin but it display doc as 0 even if there is data in particular date
here is my find plugin code
\\getting the date value on select
var saledate = document.getElementById('startdate').value;
console.log(saledate);
db.createIndex({
index: {
fields: ['Date']
}
});
db.find({
selector: {
Date: saledate, // assigning date value to the selector
},
});
}).then(function (response) {
console.log(response);
}).catch(function (err) {
console.log(err);
});
can any any one help me with code

Obtain Dexie values without using toArray()

I have the following code:
(function () {
var gameDataLocalStorageName = "myTest3";
var defaultUserSettings = {
volumes: {
musicVolume: 0.3,
sfxVolume: 0.5,
voicesVolume: 1
}
};
var savedGames = [
{
screenshot: "data uri here",
day: "1",
month: "1",
year: "1",
time: "1",
gameData: {
fonts: [{
id: 123,
name: "Arial"
}],
globalSpeeches: {
anotherVal: "something"
}
}
}
];
console.log(gameDataLocalStorageName);
console.log(defaultUserSettings);
console.log(savedGames);
/* Create db START */
var db = new Dexie(gameDataLocalStorageName);
db.version(1).stores({
usersData: ""
});
db.usersData.put(defaultUserSettings, 'userSettings');
db.usersData.put(savedGames, 'savedGames');
}());
/* Create db END */
/* Recall db START */
setTimeout(function(){
var db2 = new Dexie("myTest3");
db2.version(1).stores({
usersData: "userSettings,savedGames"
});
db2.usersData.toArray().then(function (results) {
console.log("User settings is: ", results[1]);
console.log("Saved games is: ", results[0]);
});
}, 3000);
Which runs great. However how can I obtain the data again without having to render out as an array toArray(). Currently to obtain them I have to hardcode results[0] and results[1] which is also not in the same order as I entered them into the db.
Ideally I want to do something like:
db2.get('usersData.userSettings');
db2.get('usersData.savedGames');
The sample show you are changing primary key which is not supported:
The first declaration specifies a table "usersData" with outbound primary keys:
db.version(1).stores({
usersData: ""
});
Then in the setTimout callback, you redeclare it with:
db2.version(1).stores({
usersData: "userSettings,savedGames"
});
...which means you want an inbound primary key from the property "userSettings" and and index on property "savedGames".
There are three errors here:
You cannot change declaration without incrementing version number which is not done here.
You cannot change primary key on an existing database.
Promises are not catched so you do not see the errors.
It seems what you really intend is so use Dexie as a key/value store, which is perfectly ok but much simpler to do than the sample shows.
If you put() (or add()) a value using a certain key, you retrieve the same using get().
If so, try the following:
db.version(1).stores({
usersData: "",
});
And don't forget to catch promises or await and do try/catch.
(async ()=>{
await db.usersData.put(defaultUserSettings, 'userSettings')
await db.usersData.put(savedGames, 'savedGames');
// Get using key:
const userSettings = await db.usersData.get('userSettings');
console.log("User settings is: ", userSettings);
const savedGames = await db.usersData.get('savedGames');
console.log("User settings is: ", savedGames);
})().catch(console.error);
However, putting entire arrays as values in a key/value store is not very optimal.
Maybe only have two tables "userSettings" and "savedGames" where each saved game would be its own row? Will you support multiple users or just one single user? If multiple, you could add an index "userId" to your tables.
If so, try the following:
db.version(2).stores({
userSettings: "userId" // userId is primary key
savedGames: "++gameId, userId" // incremented id and userId is foreign key
});
(async ()=>{
await db.userSettings.put({...defaultUserSettings, userId: "fooUser"});
await db.savedGames.bulkPut(savedGames.map(game =>
({...game, userId: "fooUser"}));
// Get user settings:
const userSettings = await db.usersData.get('fooUser');
console.log("User settings is: ", userSettings);
const savedGames = await db.usersData.where({userId: "fooUser"}).toArray();
console.log("Saved games for fooUser are: ", savedGames);
})().catch(console.error);

Adding to an array in MongoDB using $addToSet

I'm trying to add data to an array defined in my mongoDB called "signedUp" it is within my Timetable Schema. So far i've been able to update other fields of my schema correctly however my signedUp array always remains empty. I ensured the variable being added was not empty.
Here is my Schema
var TimetableSchema = new mongoose.Schema({
date: {
type: String,
required: true,
trim: true
},
spaces: {
type: Number,
required: true
},
classes: [ClassSchema],
signedUp: [{
type: String
}]
});
This was my latest attempt but no value is ever added to the signedUp array.
My API update request
id = {_id: req.params.id};
space = {spaces: newRemainingCapacity};
signedUp = {$addToSet:{signedUp: currentUser}};
Timetable.update(id,space,signedUp,function(err, timetable){
if(err) throw err;
console.log("updates");
res.send({timetable});
});
Thanks
You can take a look at db.collection.update() documentation. Second parameter takes update and 3rd one represents operation options while you're trying to pass your $addToSet as third param. Your operation should look like below:
id = {_id: req.params.id};
space = { $set: { spaces: newRemainingCapacity }};
signedUp = { $addToSet:{ signedUp: currentUser}};
update = { ...space, ...signedUp }
Timetable.update(id,update,function(err, timetable){
if(err) throw err;
console.log("updates");
res.send({timetable});
});
space and signedUp are together the second argument.
try this:
id = {_id: req.params.id};
space = {spaces: newRemainingCapacity};
signedUp = {$addToSet:{signedUp: currentUser}};
Timetable.update(id, {...space, ...signedUp}, function(err, timetable){
if(err) throw err;
console.log("updates");
res.send({timetable});
});

sequelize interprets date with hour = 2

I'm trying to use sequelize to search for a record in my database based in a date field:
date_from2 is this value:
2017-01-09
and sequelize interprets its as a date with hour = 2:
SELECT `id`, `user_id`, `date`, `total_visits`, `created_at`, `updated_at` FROM `table1` AS `table1` WHERE `table1`.`user_id` = 123 AND `table1`.`date` = '2017-01-09 02:00:00' LIMIT 1;
And it creates a new record everytime, instead of updating it.
When it inserts, the date is inserted with this value:
2017-01-09 00:00:00
This is my code:
where = { user_id: user_id,
date: date_from2
};
values = {
user_id: user_id,
date: date_from2,
total_visits: total_visits
};
Model.findOne({where: where}).then(function (record) {
if (!record) {
// Item not found, create a new one
Model.create(values)
.then(function () {
console.log('created!');
}).error(function (err) {
console.log('error on create');
});
} else {
// Found an item, update it
Model.update(values, {where: where})
.then(function () {
console.log('updated!');
})
.catch(function (err) {
console.log('error on update');
});
}
});
Query by just using the user's user_id and not the date if you are trying to get a specific user:
Model.findOne({where: {user_id: user_id}})
The issue is that it's storing the date differently then what you are passing in. Because of this you were never able to find the existing user and you kept creating new ones. There is nothing wrong with using UTC timezone and you should be able to convert this to any other time zone.

mongodb array data store using node js

I have to try to store my child info into MongoDB via using postman tool. But it shows me this message "message": "child info validation failed"
in postman console. child info is my collection name where I store my child info.
my requirement is to store the result in array form as below schema mentioned inside MongoDB
1). This is js child schema
userId:{
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
},
quiz:[
{
questionId:{
type: mongoose.Schema.Types.ObjectId,
ref: 'questions'
},
score:{type:String},
time:{type:String}
}
]
2). This is node js
try {
var quizArr = [];
var quizObj = {
'questionId': req.params.questionId,
'score': req.params.score,
'time': new Date().toISOString()
};
quizArr.push(quizObj);
var userObj = {
'userid': req.params.userId,
'quiz': quizArr
};
//var parseObj = Json.stringify(userObj); This line is comment
var childinfoSave = new QuizChildInfo(userObj);
childinfoSave.save(function (err) {
if (err) return next(err);
res.send("Child questionId score and date saved successfully")
console.log("Child questionId score and date saved successfully");
});
}catch(err){console.log(err);}
3). Output of postman screen
{
"message": "childinfos validation failed"
}
4). Output of console
Mongoose: mpromise (mongoose's default promise library) is deprecated, plug in your own promise library instead: http://mongoosejs.com/docs/promises.html
5). Mongo console
{
"_id" : ObjectId("57bc483169e718642ac0ac44"),
"levelsAttempted" : [ ],
"quiz" : [ ],
"__v" : 0
}
For the problem of your console,
put mongoose.Promise = global.Promise; in the file where you have established your server connection( like in my case its index.js).
And i think you may have not posted the whole code as i couldnt find childinfos in your code.

Categories