$ lookup结果显示
使用护照和nodejs和mongo / mongoose。
我将考勤logging存储在使用req.user.id作为查询的集合中,以将考勤logging绑定到注册用户。 关键字段被称为“userId”。
在尝试join时,我了解到用户集合中的_id不是stringtypes。 我一直在努力解决这个问题。 我最新的是在将req.user.id转换为ObjectId()之后尝试保存考勤logging。 但是,没有运气。 它看起来像userId仍然保存为string。 我怎样才能让这个join工作?
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; });
这是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); });
编辑:
我刚刚意识到我的rsvpsmongoose模式仍然有userId作为string。 我改变它如下:
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);
我的console.log:
console.log('rsvp: ' + rsvpList[0].user.toString());
它显示[Object object]。 我不能说这是否我的join已经工作。 我如何testingrsvpList [0] .user以查看它是否包含联合用户 ?
我很接近。 应该是:
console.log('rsvp: ' + rsvpList[0].user[0].name);