2

Using passport with nodejs and mongo/mongoose.

I store attendance records in a collection which use req.user.id as a lookup to tie the attendance records to a registered user. The key field is called "userId."

In attempting a join, I learned that the _id in the users collection is not of type string. I've been trying to work around this for quite a bit. My latest is to try to save the attendance records after converting the req.user.id to ObjectId(). Still, no luck. It looks like the userId is still saving as string. How can I get this Join to work?

router.post('/', ensureAuthenticated, function(req, res){

    var query = { userId: req.user.id };

    var update = {
        userId: new ObjectId(req.user.id),  // This is where I need to save
        response: req.body.inOrOut,
        notes: req.body.notes
    };

    //  Upsert
    var options = { upsert: true };

    // Use mongoose to save via upsert.
    RSVP.findOneAndUpdate( query, update, options, function( err, doc ) {
            if ( err ) throw err;
    });

Here is the join:

RSVP.aggregate([{
        $lookup: {
            from: "users", // collection name in db
            localField: "userId",
            foreignField: "_id",
            as: "user"
        }
    }
    ]).exec( (err, rsvpList) => {
        if (err) throw err;
        console.log(rsvpList);
    }); 

EDIT:

I just realized my mongoose schema for rsvps still had userId as string. I changed it as follows:

let mongoose = require('mongoose');
//let ObjectId = require('mongodb').ObjectId;

// RSVP Schema
var RSVPSchema = mongoose.Schema({
    userId: {
        //type: String,
        type: mongoose.Schema.Types.ObjectId,
        index:true
    },
    response: {
        type: String
    },
    notes: {
        type: String
    },
});

var RSVP = module.exports = mongoose.model('RSVP', RSVPSchema);

My console.log:

console.log('rsvp: ' + rsvpList[0].user.toString());

It shows [Object object]. I can't tell by this whether my join has worked. How can I test rsvpList[0].user to see if it contains the joined user?

Neil Lunn
  • 148,042
  • 36
  • 346
  • 317
Jeff Matthews
  • 602
  • 2
  • 7
  • 17
  • JavaScript 101. `console.log()` does not "deep serialize" objects. Use `JSON.stringify` as [demonstrated in the linked answer](https://stackoverflow.com/a/4293047/2313887) – Neil Lunn Nov 16 '17 at 00:59

1 Answers1

0

I was close. It should have been:

console.log('rsvp: ' + rsvpList[0].user[0].name);
Jeff Matthews
  • 602
  • 2
  • 7
  • 17