Search code examples
node.jsmongodbkoaswig-templatemonk

How to Retrieve MongoDb collection Id with Monk


I'm trying to do a very simple app 'todo app' on koajs with swig and I have succeeded in inserting data to Mongodb, in my case the name of the db is 'mytodos' and the collection is 'todos'.

How can I retrieve the '_id' of a document? I tried doing this:

index.html (this lists the todo items)

<div class="todoListClass">
  <p>
    <strong>Your todo list:</strong> {{todos.length}}
    {% for todo in todos%}
    <li>{{todo.text1}} <span>
    <a href="/todo/delete/{{todo._id}}">Delete</a></span></li>
    {%endfor%}
  </p>
</div>

but I can't seem to get the result that I want. It just returns '[Object][object]'.


Solution

  • The _id field of your todo item is loaded from mongodb for displaying the _id field which is of type ObjectId you will need to get a string representation by calling _id.toString().

    <div class="todoListClass">
      <p>
        <strong>Your todo list:</strong> {{todos.length}}
        {% for todo in todos%}
        <li>{{todo.text1}} <span>
        <a href="/todo/delete/{{todo._id.toString()}}">Delete</a></span></li>
        {%endfor%}
      </p>
    </div>