Mongoose-caching part of the reference subdoc about creation

I have a simple schema with links. But I don't want to fill out a reference document for every request. Instead, I want to cache a part (just one attribute) in the referenced document.

Simple example outline:

User
  - displayName
  (....stuff....)

Posts
  - title
  - content
  - user (reference?)

      

When I used links and population as requested, my PostSchema looks like this:

var PostSchema = new Schema({
    ...
    user: {
            type: Schema.ObjectId,
            ref: 'User'
        }
})

      

But I want to store (cache) only displayName (not other stuff in User) and _id in the column when it is created . My users should change PostSchema like this:

user: {
    _id: {
        type: Schema.ObjectId,
        ref: 'User'
    },
    displayName: String
}

      

when creating the post I am doing:

var post = new Post(req.body);
post.user._id = req.user._id;
post.user.displayName = req.user.displayName;

      

The problem is this: it looks like _id is now a referenced user, resulting in an absurd user._id._id. Also my isCreator-middleware now needs to convert the _id to a string:

exports.isCreator = function(req, res, next) {
    if (req.post.user._id.toString() !== req.user._id.toString()) {
        return res.status(403).send('User is not authorized');
    }
    next();
};

      

This may not be the best solution. So my question is what is best for this case?

+3


source to share





All Articles