Sunday 28 May 2017

NodeJS and mongoose populating subdocument

I currently have two models: "User" and "Note". A User can create notes. This is what the "User" model currently looks like:

UserSchema = new mongoose.Schema({
    email:  String,
    password: String,
    notes: [
        {
            type: mongoose.Schema.Types.ObjectId,
            ref: "Note"
        }
    ]
});

And this is what the "Note" model currently looks like:

var NoteSchema = mongoose.Schema({
    creator: {
        type: mongoose.Schema.Types.ObjectId,
        required: true
    },
    dateOfCreation: {
        type: Date,
        default: Date.now
    },
    title: String,
    bodyText: String,
    binder: String,
    type: {
        type: String,
        default: "Text"
    },
    audioPath: String,
    summarizedBodyText: String,
    summarizedAudioNote: String
});

And this is my POST route which creates a note and pushes it to the appropriate user:

app.post("/newNote", function(req, res) {
    var newNote = {creator: req.user._id.toString(), title : "Untitled note"}
    Note.create(newNote, function(error, newNote) {
        if (error) {
            console.log(error);
        }
        else {
            User.findByIdAndUpdate(
                req.user._id.toString(),
                {
                    $push: {
                        "notes": newNote
                    }
                },
                {
                    safe: true,
                    upsert: true,
                    new : true
                },
                function(err, model) {
                    console.log(err);
                }
            );
            res.render("interface");
        }
    });
});

This route pushes the note _id to the user:

enter image description here

However, I would like the full note schema to appear in the user's document, not just the ObjectID. How would I go about doing this? Thanks so much!



via Russell C.

No comments:

Post a Comment