Search code examples
node.jsmongodbmongoosemiddleware

Mongoose Model.find -> Edit -> Callback?


Sorry for the vague title, but what I'm trying to do is the following: I've got 2 mongoose Models: posts and users (which can be the author of a post)

const Post = new Schema({
    title: {type: String, required: true, unique: true},
    content: {type: String, required: true},
    date_created: {type: Date, required: true, default: Date.now},
    authorId: {type: String, required: true},             // ObjectId
    author: {type: Schema.Types.Mixed},
    page: {type: Boolean, required: true, default: false}
});

post.find()
mongoose sends query to MongoDB
MongoDB returns documents
Middleware that retrieves the author based on the authorId property
Add found user to the posts author field
post.find callback

Is this possible?


Solution

  • yes, mongoose document references and population will do this for you.

    const Post = new Schema({
        // ...
        author: {type: mongoose.Schema.Types.ObjectId, required: true, ref: "User"}
    });
    

    the ref: "User" tells Mongoose to use the "User" type as the object type. Be sure you have a "User" model defined with Mongoose or this will fail.

    to load the full object graph, use the populate method of a query:

    
    Post
      .findOne(/* ... */)
      .populate('author')
      .exec(function (err, story) {
        // ...
    
      });
    

    P.S. I cover this and more in my MongooseJS Fundamentals screencast package.