質問

I'm returning my model to my view something like this:

User.findOneById('xxx', function(err, result){
    res.render('viewName', {user: result});
}

Then, on my view, I have a script block, that I'm trying to assign the user to a variable:

<script id="foundBusiness" type="text/javascript">
    var user = <%-user%>
</script>

This renders as follows as the HTML

var user = { __v: 0,
  _id: 5315b7b9caaf52e624070002,
  firstName: 'Alex',
  lastName: 'Brown',
  password: '$2a$10$Zs/6JmB3Rq5dddHvjZNUse9vl.8z3hJO.LUGBqMEE.vBMk4lVuav.'}

My issue is around the _id field
This is obviously not valid Javascript, and as such, an error occurs:

SyntaxError: Unexpected token ILLEGAL

What am I doing wrong?

役に立ちましたか?

解決

From the horse's mouth

ObjectIds contain the raw MongoDB binary and don't work with templating so we provide the id convenience method to convert them to hexstrings

https://github.com/LearnBoost/mongoose/issues/548

One possible solution -

User.findOneById('xxx', function(err, result){
    result._id = result._id.toHexString();
    res.render('viewName', {user: result});
}

I think assigning it to result.id would also work.

result._id = result.id;
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top