0

Hello I'd like to know if it's possible to create pseudo properties on Mondodb. This is, currently I have a collections users like this:

{_id: (_1), name: "user1", secret: "1"}
{_id: (_2), name: "user2", secret: "2"}

When I query the database. I do something like:

function getuser(objectId) {
  db.users.find({_id : objectId}).toArray(function(err, result) {
    x = result[0];
    x.pseudoField1 = hash(secret); 
    return x;
  });
}

Then I do some operations on the x object, and return to put on the database, but before I have to filter the not needed properties, so I do:

y = {}
y._id = x._id
y.name = x.name
y.secret = x.secret
db.users.update({_id: y._id}, y);

What I'd like to do is know if there is any way to make the databse automaticaly return an object with the pseudoField1 with the function I want, and furthermore, when I issue an update with x, only the fields _id, name and secret get updated.

laggingreflex
  • 32,948
  • 35
  • 141
  • 196
xtrm0
  • 124
  • 9
  • How about implementing this logic in a custom function and then only using that function as a proxy for your collection's update/insert/find methods? – Lix Jun 01 '15 at 13:51
  • 1
    if you are using mongoose.. use virtuals – codeofnode Jun 01 '15 at 13:58

1 Answers1

0

When you want to calculate fields on the database, you can use an aggregation pipeline with a $project stage. The aggregation frameworks offers some simple arithmetic operators to create fields which are derived from values of other fields, but implementing a complex hash function is likely far too complicated to do on the database.

Your second requirement - telling MongoDB to ignore a certain field when inserting - isn't possible out-of-the-box. But what you can do is remove the field from the document before saving it. You can also use an object-document wrapper like Mongoose which allows you to define schemas and exclude certain fields from storing them in the database.

Community
  • 1
  • 1
Philipp
  • 67,764
  • 9
  • 118
  • 153