我有此代码:
<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]"
,所以这无济于事。
这是mongoDB中的_id
字段
"_id": {
"$oid": "5bc9d28270e5375dfbfe17fd"
},
那么如何将用户的_id
作为字符串传递?
答案 0 :(得分:1)
要获取id的十六进制表示,可以使用.valueOf()
。这里有更多方法和示例:https://docs.mongodb.com/manual/reference/method/ObjectId.valueOf/#ObjectId.valueOf