I have an app with RoR and Mongoid, and I have a Boolean field in a Document. But when I save the document and see the mongo, it return 0 or 1.
Why mongoid don't save true or false? There's any reason?
I try to find it on documentation of mongoid, but don't have success...
True and False values are on the BSON spec as "\x00" and "\x01", as mongoid passes the objects to mongodb using the BSON protocol, true and false are converted to 0 and 1. You can see the code in here https://github.com/mongodb/bson-ruby/blob/master/lib/bson/true_class.rb#L25
Related
I have a structure that looks kind of like this:
{
'foo': 'bar',
'isBaz': false
}
and the following Repository code
repository.findByIsBazIsFalse();
I figured that would only return records where isBaz is false, but it's also returning records where isBaz is set to true. My initial guess is that the field starts with the word 'is' which is a reserved keyword in the spring/mongo query.
FWIW I also tried via annotation but no luck
#Query("{isBaz:false}")
Does anyone know how to make it work without renaming the variable to 'baz'?
Make sure this field is defined as boolean and it should work!
private boolean isBaz;
repository.findByIsBazIsFalse();
[main] o.m.d.p.c :Sending command '{"find": "collection", "filter": {"isBaz": false}, ...}'
Let say I have a collection. I want to change the field name and value in the whole collection like this
Current:
language:"en",
documentId:"123"
Desired:
languages:["en"],
documentIds:["123"]
db.foo.... Thank you in advance
Query
empty filter {} and updateMany to update all collection
you can use "$field" to refer to filed and and array literals
and $unset to remove the old fields
*pipeline update requires MongodDB >= 4.2
Test code here
updateMany({},
[{"$set": {"languages": ["$language"], "documentIds": ["$documentId"]}},
{"$unset": ["language", "documentId"]}])
I need some help using Model.find() in Mongoose.
I’ve added a boolean field isPrivate to a data model so users can specify if they want their entries to be publicly viewable, or viewable only by them. Here’s the current index function which returns all documents:
Snippet.find({})
.populate('addedBy')
.then(snippets => res.json(snippets))
.catch(err => {res.json(err)})
}
I need to modify this so that it returns all documents where isPrivate === false AND all documents where isPrivate === true if the current user ID matches the document’s field that logged the user ID when created. Any ideas? Making either of these queries is simple, but I need to make both of them.
I’m not sure how to use Model.find() with two sets of parameters. Is this possible?
Or is there a way to make two Mongoose queries and combine the results?
If I understand correctly what your requirements are, using the $or operator should help:
Snippet.find({
$or: [
{isPrivate: false},
{isPrivate: true, creatorField: currentUserId}
]
})
.populate('addedBy')
.then(snippets => res.json(snippets))
.catch(err => {res.json(err)}) }
This will return all documents where isPrivate is false, as well as all documents where isPrivate is true and the creator is the current user. (you'll of course have to adapt creatorField and currentUserId)
If however, you want to query on the populated field addedBy, you'll have to use the aggregation framework with the $lookup operator.
I use this ngRepeat and now I will filter for communicationUserConnections where communicationUserConnection#executed is true.
IS there a possibility to do this
data-ng-repeat="communicationUserConnection in vm.communicationUserConnections | filter:executed=vm.mySelectedValue.
If vm.mySelectedValue is true than show all communicationUserConnection where executed == true, otherwise show all communicationUserConnection's
Try following:
data-ng-repeat="communicationUserConnection in vm.communicationUserConnections |filter:{'executed':vm.mySelectedValue}"
I'm referring to this blog on how to use postgresql arrays in Rails 4. To be more precise, I'm using Rails 4.1.8.
I would like to enforce that the array should not be empty(should have at least one or more values) wrt the below table definition for the phones attribute.
Setting null: false as done below prevents me from doing a Contacts.create(phones: nil), but Contacts.create(phones: []) saves to the database.
class CreateContacts < ActiveRecord::Migration
def change
create_table :contacts do |t|
t.string :name
t.text :phones, array: true, null: false
end
end
end
What constraint can I use to ensure that Contacts.create(phones: []) raises an error saying that there should be at least one entry within the array?
A regular presence validation should meet your requirement, since the empty array is not present?.
class Contact < ActiveRecord::Base
validates :phones, presence: true
end
I suggest you use a serialized attribute instead.
class CreateContacts < ActiveRecord::Migration
def change
create_table :contacts do |t|
t.string :name
t.text :phones, null: false
end
end
end
And in your model:
class Contact < ActiveRecord::Base
serialize :phones
validate :phones, presence: true
before_validation :clean_empty_array
private
def clean_empty_array
self.phones = phones.presence
end
end
Note that I added a before_validation cleaning method, to turn empty arrays into nil using presence ([].presence => nil; ["1"].presence => ["1"]). As an alternative, you could use attribute_normalizer gem to handle this kind of data normalization if you have this requirement in more places of your application.
EDIT: after discussion in the comments, serialize seems to be not the best way to go, since it carries important caveats such as querying issues. Thanks to #muistooshort for pointing these out. Also, the before_validation is not needed, since a presence: true validation is equivalent to what was proposed in the before_validation.
So the final solution to the question would involve keeping Postgresql array support and just validating against phones presence.
In short: keep array: true in your migration file and add this validation to your model:
class Contact < ActiveRecord::Base
validate :phones, presence: true
end