Reputation: 156
To ease load on my MongoDB server, I want to cache some objects from Waterline in Redis. To achieve this, I have to serialize the object to JSON.
My question is, how can I construct my JSON back to an instance of the Waterline model, with datatype handling, member functions etc, making this transparent to the consuming code?
I have also wanted this whenever I run native MongoDB queries, giving me objects with native ObjectIDs, mismatching date types etc.
User.findOne(id, function (err, user) {
// to string and back again, could be stored in cache in the meantime
var object = JSON.parse(JSON.stringify(user));
var user = new User(object); //doesn't work
var user = User.toObject(object); // doesn't work
}
Upvotes: 3
Views: 1328
Reputation: 3993
According to this issue, this should work
var user = new User._model(object);
Pay attention about the values that you insert. The new object should really fit what you had before the stringification.
Upvotes: 5
Reputation: 2051
What kind of cache
do you want to approach?
var object = JSON.parse(JSON.stringify(user));
won't store all of the information. JSON is different from JavaScript object. Which user
is JavaScript object, that is created by Sails's Waterline engine. It has methods like save
, but when you turn it into JSON, the method will be gone.
Either var user = new User(object);
or var user = User.toObject(object);
won't work, because User
is not a constructor, it just a shorthand to sails.models.user
which represent the User
model at /api/models/User.js
.
If you want to query fast, you must store your data
in your Redis, and retrieve from it later.
By that mean, you should save your user
from the main database to your redis by insert it manually to your redis, then retrieve it later. But all of your main database model characteristic is will be gone, except you copy your main database model (User
in this case) to your redis User
model (or whatever you named it).
Upvotes: 1