updating a doc couchdb - couchdb

Please bear with me if my question is simple, I'm so new to couchDB:
I have this document:
{
Name : Raju
age : 23
Designation : Designer
}
How can I update my document to:
{
Name : Raju
age : 23
}
Can I use insertfor the document with my desired data which is {Name : Raju, age : 23} object? Does it delete Designation field?

In short, you can do that, CouchDB does not attempt to merge updates, just updates the doc to whatever you sent it. Please take a moment to read http://docs.couchdb.org/en/1.6.1/intro/api.html#documents
It is a very simple, well written bunch of examples. I would encourage you to read the couchdb docs first if you new to it.

Related

Prob find latest collection

I don't find much information about this problem to solve.
On my mongodb I create a collection every 60 seconds with the name "test "+ date.now(). So far everything works ok. It creates me different collections with the name test XXXXXX1, test XXXXX2 etc.
I have problems with the mongoose.find() method. I can't find my last created collection.
let test = mongoose.model('test' + date.now(), Schema);
test.find({}, function (err, response) {});
How do I find the latest collection in stream? Thank you!
Mongo ,By default , does not support sequence .
for that purpose you're going to have to add specific field for sorting or sort your fields based on your current field properties.
After that you have to use .sort() cursor method :
Collection.find().sort([...]);
Read this article for more info

SDD Payment via Automated Action (Odoo v13)

Unfortunately Odoo has removed the automatic SSD payment from v12 to v13, which is crucial for me. Therefore I try to reproduce the behavior via an automated action and came quite far I guess.
I created an Automated Action that watches all invoices in draft and runs a python code if the invoice is set from draft to not draft. But unfortunately I get an error as soon as I try to post an invoice:
"Database fetch misses ids (('10',)) and has extra ids ((10,)), may be caused by a type incoherence in a previous request"
As far as I know this is related to type transformation, but as I am new to python & odoo, I am not sure how to transform the odoo datatypes correctly. Does anyone have a hint?
Here's the python code that should be executed:
payment = env['account.payment'].create({
'payment_method_id' : '6',
'partner_id': record.partner_id.id,
'journal_id' : '10',
'amount' : record.amount_residual
})
The ids are double checked and link to the correct entries:
payment_method_id '6' = my bank account
journal_id '10' = SDD Payment
Below please find the current domain applied to the Automated Action.
Any hints or help is much appreciated!
Many thanks.
Best regards,
Christian
CBfac
On the many2one field you have to assign the ID.
Code Correction:
payment = env['account.payment'].create({
'payment_method_id' : 6,
'partner_id': record.partner_id.id,
'journal_id' : 10,
'amount' : record.amount_residual
})
For everyone who needs automatic SDD payments in Odoo v13, here's the Automated Action that works for me (one more, thanks #Dipen Sah for your assistance):
Modell: account.move
Trigger: on update
Action: Execute python code
Domain (before update):
["&","&","&","&",["sdd_paying_mandate_id","=",False],["partner_id.sdd_mandate_ids","!=",False],["type","=","out_invoice"],["invoice_payment_state","=","not_paid"],["state","=","draft"]]
Domain (after update):
["&","&","&","&",["sdd_paying_mandate_id","=",False],["partner_id.sdd_mandate_ids","!=",False],["type","=","out_invoice"],["invoice_payment_state","=","not_paid"],["state","!=","draft"]]
Python code to execute:
payment = env['account.payment'].create({
#'name' : env['ir.sequence'].next_by_code('account.payment.customer.invoice'),
#'payment_type': 'inbound',
#'partner_type' : 'customer',
'payment_method_id' : 6,
'partner_id': record.partner_id.id,
'journal_id' : 10,
'amount' : record.amount_residual}).post()
You have to upate the journal and payment_method ids within the python code to match your IDs in order to get the action running properly.
Any improvements and/or feedback are welcome.
Best regards,
Christian

Error is null in Mongo? [duplicate]

Following is my user schema in user.js model -
var userSchema = new mongoose.Schema({
local: {
name: { type: String },
email : { type: String, require: true, unique: true },
password: { type: String, require:true },
},
facebook: {
id : { type: String },
token : { type: String },
email : { type: String },
name : { type: String }
}
});
var User = mongoose.model('User',userSchema);
module.exports = User;
This is how I am using it in my controller -
var user = require('./../models/user.js');
This is how I am saving it in the db -
user({'local.email' : req.body.email, 'local.password' : req.body.password}).save(function(err, result){
if(err)
res.send(err);
else {
console.log(result);
req.session.user = result;
res.send({"code":200,"message":"Record inserted successfully"});
}
});
Error -
{"name":"MongoError","code":11000,"err":"insertDocument :: caused by :: 11000 E11000 duplicate key error index: mydb.users.$email_1 dup key: { : null }"}
I checked the db collection and no such duplicate entry exists, let me know what I am doing wrong ?
FYI - req.body.email and req.body.password are fetching values.
I also checked this post but no help STACK LINK
If I removed completely then it inserts the document, otherwise it throws error "Duplicate" error even I have an entry in the local.email
The error message is saying that there's already a record with null as the email. In other words, you already have a user without an email address.
The relevant documentation for this:
If a document does not have a value for the indexed field in a unique index, the index will store a null value for this document. Because of the unique constraint, MongoDB will only permit one document that lacks the indexed field. If there is more than one document without a value for the indexed field or is missing the indexed field, the index build will fail with a duplicate key error.
You can combine the unique constraint with the sparse index to filter these null values from the unique index and avoid the error.
unique indexes
Sparse indexes only contain entries for documents that have the indexed field, even if the index field contains a null value.
In other words, a sparse index is ok with multiple documents all having null values.
sparse indexes
From comments:
Your error says that the key is named mydb.users.$email_1 which makes me suspect that you have an index on both users.email and users.local.email (The former being old and unused at the moment). Removing a field from a Mongoose model doesn't affect the database. Check with mydb.users.getIndexes() if this is the case and manually remove the unwanted index with mydb.users.dropIndex(<name>).
If you are still in your development environment, I would drop the entire db and start over with your new schema.
From the command line
➜ mongo
use dbName;
db.dropDatabase();
exit
I want to explain the answer/solution to this like I am explaining to a 5-year-old , so everyone can understand .
I have an app.I want people to register with their email,password and phone number .
In my MongoDB database , I want to identify people uniquely based on both their phone numbers and email - so this means that both the phone number and the email must be unique for every person.
However , there is a problem : I have realized that everyone has a phonenumber but not everyone has an email address .
Those that don`t have an email address have promised me that they will have an email address by next week. But I want them registered anyway - so I tell them to proceed registering their phonenumbers as they leave the email-input-field empty .
They do so .
My database NEEDS an unique email address field - but I have a lot of people with 'null' as their email address . So I go to my code and tell my database schema to allow empty/null email address fields which I will later fill in with email unique addresses when the people who promised to add their emails to their profiles next week .
So its now a win-win for everyone (but you ;-] ): the people register, I am happy to have their data ...and my database is happy because it is being used nicely ...but what about you ? I am yet to give you the code that made the schema .
Here is the code :
NOTE : The sparse property in email , is what tells my database to allow null values which will later be filled with unique values .
var userSchema = new mongoose.Schema({
local: {
name: { type: String },
email : { type: String, require: true, index:true, unique:true,sparse:true},
password: { type: String, require:true },
},
facebook: {
id : { type: String },
token : { type: String },
email : { type: String },
name : { type: String }
}
});
var User = mongoose.model('User',userSchema);
module.exports = User;
I hope I have explained it nicely .
Happy NodeJS coding / hacking!
In this situation, log in to Mongo find the index that you are not using anymore (in OP's case 'email'). Then select Drop Index
Check collection indexes.
I had that issue due to outdated indexes in collection for fields, which should be stored by different new path.
Mongoose adds index, when you specify field as unique.
Well basically this error is saying, that you had a unique index on a particular field for example: "email_address", so mongodb expects unique email address value for each document in the collection.
So let's say, earlier in your schema the unique index was not defined, and then you signed up 2 users with the same email address or with no email address (null value).
Later, you saw that there was a mistake. so you try to correct it by adding a unique index to the schema. But your collection already has duplicates, so the error message says that you can't insert a duplicate value again.
You essentially have three options:
Drop the collection
db.users.drop();
Find the document which has that value and delete it. Let's say the value was null, you can delete it using:
db.users.remove({ email_address: null });
Drop the Unique index:
db.users.dropIndex(indexName)
I Hope this helped :)
Edit: This solution still works in 2023 and you don't need to drop your collection or lose any data.
Here's how I solved same issue in September 2020. There is a super-fast and easy way from the mongodb atlas (cloud and desktop). Probably it was not that easy before? That is why I feel like I should write this answer in 2020.
First of all, I read above some suggestions of changing the field "unique" on the mongoose schema. If you came up with this error I assume you already changed your schema, but despite of that you got a 500 as your response, and notice this: specifying duplicated KEY!. If the problem was caused by schema configuration and assuming you have configurated a decent middleware to log mongo errors the response would be a 400.
Why this happens (at least the main reason)
Why is that? In my case was simple, that field on the schema it used to accept only unique values but I just changed it to accept repeated values. Mongodb creates indexes for fields with unique values in order to retrieve the data faster, so on the past mongo created that index for that field, and so even after setting "unique" property as "false" on schema, mongodb was still using that index, and treating it as it had to be unique.
How to solve it
Dropping that index. You can do it in 2 seconds from Mongo Atlas or executing it as a command on mongo shell. For the sack of simplicity I will show the first one for users that are not using mongo shell.
Go to your collection. By default you are on "Find" tab. Just select the next one on the right: "Indexes". You will see how there is still an index given to the same field is causing you trouble. Just click the button "Drop Index". Done.
So don't drop your database everytime this happens
I believe this is a better option than just dropping your entire database or even collection. Basically because this is why it works after dropping the entire collection. Because mongo is not going to set an index for that field if your first entry is using your new schema with "unique: false".
I faced similar issues ,
I Just clear the Indexes of particular fields then its works for me .
https://docs.mongodb.com/v3.2/reference/method/db.collection.dropIndexes/
This is my relavant experience:
In 'User' schema, I set 'name' as unique key and then ran some execution, which I think had set up the database structure.
Then I changed the unique key as 'username', and no longer passed 'name' value when I saved data to database. So the mongodb may automatically set the 'name' value of new record as null which is duplicate key. I tried the set 'name' key as not unique key {name: {unique: false, type: String}} in 'User' schema in order to override original setting. However, it did not work.
At last, I made my own solution:
Just set a random key value that will not likely be duplicate to 'name' key when you save your data record. Simply Math method '' + Math.random() + Math.random() makes a random string.
I had the same issue. Tried debugging different ways couldn't figure out. I tried dropping the collection and it worked fine after that. Although this is not a good solution if your collection has many documents. But if you are in the early state of development try dropping the collection.
db.users.drop();
I have solved my problem by this way.
Just go in your mongoDB account -> Atlast collection then drop your database column. Or go mongoDB compass then drop your database,
It happed sometimes when you have save something null inside database.
This is because there is already a collection with the same name with configuration..Just remove the collection from your mongodb through mongo shell and try again.
db.collectionName.remove()
now run your application it should work
I had a similar problem and I realized that by default mongo only supports one schema per collection. Either store your new schema in a different collection or delete the existing documents with the incompatible schema within the your current collection. Or find a way to have more than one schema per collection.
I got this same issue when I had the following configuration in my config/models.js
module.exports.models = {
connection: 'mongodb',
migrate: 'alter'
}
Changing migrate from 'alter' to 'safe' fixed it for me.
module.exports.models = {
connection: 'mongodb',
migrate: 'safe'
}
same issue after removing properties from a schema after first building some indexes on saving. removing property from schema leads to an null value for a non existing property, that still had an index. dropping index or starting with a new collection from scratch helps here.
note: the error message will lead you in that case. it has a path, that does not exist anymore. im my case the old path was ...$uuid_1 (this is an index!), but the new one is ....*priv.uuid_1
I have also faced this issue and I solved it.
This error shows that email is already present here. So you just need to remove this line from your Model for email attribute.
unique: true
This might be possible that even if it won't work. So just need to delete the collection from your MongoDB and restart your server.
It's not a big issue but beginner level developers as like me, we things what kind of error is this and finally we weast huge time for solve it.
Actually if you delete the db and create the db once again and after try to create the collection then it's will be work properly.
➜ mongo
use dbName;
db.dropDatabase();
exit
Drop you database, then it will work.
You can perform the following steps to drop your database
step 1 : Go to mongodb installation directory, default dir is "C:\Program Files\MongoDB\Server\4.2\bin"
step 2 : Start mongod.exe directly or using command prompt and minimize it.
step 3 : Start mongo.exe directly or using command prompt and run the following command
i) use yourDatabaseName (use show databases if you don't remember database name)
ii) db.dropDatabase()
This will remove your database.
Now you can insert your data, it won't show error, it will automatically add database and collection.
I had the same issue when i tried to modify the schema defined using mangoose. I think the issue is due to the reason that there are some underlying process done when creating a collection like describing the indices which are hidden from the user(at least in my case).So the best solution i found was to drop the entire collection and start again.
If you are in the early stages of development: Eliminate the collection. Otherwise: add this to each attribute that gives you error (Note: my English is not good, but I try to explain it)
index:true,
unique:true,
sparse:true
in my case, i just forgot to return res.status(400) after finding that user with req.email already exists
Go to your database and click on that particular collection and delete all the indexes except id.

How do I convert this MongoDB Date value?

This has me stumped. I am fairly new to noSql, and node.js development. So running into moments of what the heck are pretty common. Yet I cannot come to grips with this one on my own.
We are inserting documents into a mongo user collection and everything is working as it should. What I do not get and would like to have some insight on...is the creation of my users, the _id value is also a date stamp. I can sort on this field and user names corresponds to sign up log entries. Yet for the life of me I cannot determine a way to convert this to a normal time-stamp that is human readable.
520193b4571be99a06000031 is typical date code.
Here is a collection snip.
{
"_id" : ObjectId("520193b4571be99a06000031"),
"email" : "this_user#gmail.com",
"google" : {
"email" : "XXXXXXXXXXXXXXXXXXXXXX",
"expires" : ISODate("2012-10-11T18:30:13.611Z"),
"accessToken" : "A_Reallly_REALLY_LONG one!!!!####$$$$$$%%%%%%%"
},
"login" : "google:XXXXXXXXXXXXXXXXXXXXXX"
}
Per the docs:
ObjectId("520193b4571be99a06000031").getTimestamp()
look at here
http://docs.mongodb.org/manual/reference/object-id/
or http://api.mongodb.org/java/2.0/org/bson/types/ObjectId.html
and create an objectID and get date from there

How to index CouchDB with Elastic Search River: In plain english

I really don't know what's going on with my configuration, but I'm just not able to query anything after indexing (don't even know if I'm doing the indexing part correctly). Could someone please tell me what each of the following means and should be?
I have a CouchDB database called bestdb. Inside this database I have document types like product and customer.
Now I installed elastic search version 0.18.7 and the corresponding couchdb river. I started elastic search and couchdb. I set the network.host of elasticsearch to be an ip address: 10.0.0.129 . I followed the instructions in the tutorial :
curl -XPUT '10.0.0.129:9200/_river/{A}/_meta' -d '{
"type" : "couchdb",
"couchdb" : {
"host" : "localhost",
"port" : 5984,
"db" : "bestdb",
"filter": null
},
"index" : {
"index" : "{B}",
"type" : "{C}",
"bulk_size" : "100",
"bulk_timeout" : "10ms"
}
}'
{A}: What's this? My understanding is that this is just an internal elastic search index right? It's not being used for querying or searching right? So this could be any name right?
{B}: What's this index? How is this different from the one above? What should the value of this be in my scenario?
{C}: Is this related to the Document Type in couchdb, like product or customer ?
The online tutorial just sets everything to be the same value. How would my curl statement look like if I wanted to query all product documents or customer documents?
Thank you to whoever that clears things up a bit for me.
Regards,
Mark Huang
kimchy's documentation often leaves a little bit to the imagination. :-)
A is the river name. A river is just an ES document, stored in an index named _river, a type named whatever you want, and a doc id _meta.
B & C is the local index/_type that your bestdb couchdb _changes stream will get indexed into. These can be overridden by _index and _type fields in your couchdb documents. If none of the above is supplied, they'll default to your couchdb instance name bestdb/bestdb.

Resources