javascript - 节点读取字符串作为对象
问题描述
我有这个代码:
<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
用户的作为字符串传递呢?
解决方案
要获得 id 的十六进制表示,您可以使用.valueOf()
. 更多方法和示例在这里:https ://docs.mongodb.com/manual/reference/method/ObjectId.valueOf/#ObjectId.valueOf
推荐阅读
- javascript - 根据部分类名在 DOM 中搜索元素
- angular7 - 如何使用“相对于”属性导航到兄弟路线?
- python - 内存可用时出现 GPU 运行时错误
- input - 你如何在python3中输入的开头和结尾放置文本
- unreal-engine4 - 如何使用 Is Valid 检查来完成我在 UE4 中的评分系统?
- c - 为什么指针在 C 中不会改变它的值?
- node.js - google oauth 用 express 反应原生的程序是什么
- python - discord.errors.HTTPException:400 Bad Request(错误代码:50006):无法发送空消息
- beautifulsoup - 如何提取多次出现的特定标签的文本
- javascript - apache echarts中刻度之间的中心标签