【问题标题】:$lookup result shows [object Object] [duplicate]$lookup 结果显示 [object Object] [duplicate]
【发布时间】:2018-04-28 22:04:48
【问题描述】:

将护照与 nodejs 和 mongo/mongoose 一起使用。

我将出勤记录存储在一个集合中,该集合使用 req.user.id 作为查找以将出勤记录与注册用户联系起来。关键字段称为“userId”。

在尝试加入时,我了解到 users 集合中的 _id 不是字符串类型。我一直在尝试解决这个问题。我最新的是在将 req.user.id 转换为 ObjectId() 后尝试保存考勤记录。尽管如此,还是没有运气。看起来 userId 仍然保存为字符串。我怎样才能让这个加入工作?

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;
    });

这是连接:

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);
    }); 

编辑:

我刚刚意识到 rsvps 的猫鼬模式仍然有 userId 作为字符串。我修改如下:

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('rsvp: ' + rsvpList[0].user.toString());

它显示[对象对象]。我不能由此判断我的加入是否有效。如何测试 rsvpList[0].user 以查看它是否包含加入的 user

【问题讨论】:

标签: javascript node.js mongodb


【解决方案1】:

我很接近。应该是:

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

【讨论】:

    猜你喜欢
    • 2023-02-23
    • 2014-07-28
    • 2019-04-18
    • 2021-09-14
    • 1970-01-01
    • 2012-05-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多