首页 > 解决方案 > 节点读取字符串作为对象

问题描述

我有这个代码:

<a class="btn-primary btn" href="/employer/booth/<%= user._id.toString() %>"
        <% console.log(typeof user._id, user._id) %>
   target="_blank">
    Preview your booth
</a>

这个 console.log 的结果是这样的:object 5bc9d28270e5375dfbfe17fd

为什么?为什么用护照创建的通用 _id 当它显然是一个字符串时被视为一个对象?

我试过这样做.toString(),但这导致我的路由器出现另一个错误。这是代码:

router.get('/booth/:emp_id', async (req, res, next) => {
    const mongoose = require('mongoose');
    // For reports
    const {emp_id} = req.params;
    console.log('here', emp_id);
    console.log(typeof  emp_id);
    console.log(JSON.stringify(emp_id));
    const eventId = await GeneralInfo.findOne().then(r => r.activeEventId).catch(e => console.log(e));
    const event = await Event.findById(eventId).catch(e => console.log(e));
    Event.updateOne({'attendants.employers.id': mongoose.Types.ObjectId(emp_id)}, {$addToSet: {"attendants.employers.$.boothVisits": req.user._id}}, {$upsert: true}).catch(e => console.log(e));
    var postings = await Posting.find({
        'creatorId': emp_id,
        'visible': true,
        'eventId': eventId,
    }).catch(e => console.log(e));
    const acc = await Account.findById(emp_id);
    // const logo = await functions.downloadFile(req, res);
    const logo = await functions.downloadFile(acc.employer.logo);
    console.log(logo);
    res.render('users/employer/booth', {
        title: 'Employer Booth',
        user: req.user,
        postings: postings,
        employer: acc,
        event: event,
        logo: logo,
    });
});

如果我这样做,那么传递一个字符串我得到这个:

(node:15508) UnhandledPromiseRejectionWarning: Error: Argument passed in must be a single String of 12 bytes or a string of 24 hex characters
at new ObjectID (/home/alex/Documents/Projects/ontario-job-portal/node_modules/mongodb-core/node_modules/bson/lib/bson/objectid.js:57:11)
at ObjectID [as ObjectId] (/home/alex/Documents/Projects/ontario-job-portal/node_modules/mongodb-core/node_modules/bson/lib/bson/objectid.js:38:43)
at router.get (/home/alex/Documents/Projects/ontario-job-portal/routes/employer.js:68:68)
at <anonymous>

因为出于某种原因,req.params.emp_id[object Object]。如果我尝试JSON.stringify我得到"[object Object]",那么这是非常无益的。

这是_id来自 mongoDB 的字段

"_id": {
    "$oid": "5bc9d28270e5375dfbfe17fd"
},

那么如何将_id用户的作为字符串传递呢?

标签: javascriptnode.jsexpress

解决方案


要获得 id 的十六进制表示,您可以使用.valueOf(). 更多方法和示例在这里:https ://docs.mongodb.com/manual/reference/method/ObjectId.valueOf/#ObjectId.valueOf


推荐阅读