Weiheng Li Weiheng Li - 2 months ago 7
Node.js Question

If _id has any special usage in JavaScript?

I have one nodejs app, which define answer like this:

var answerSchema = mongoose.Schema({
session : String, // the ID of the session
question : String, // the ID of the question
answer : Number // the selected answer (1-5)
});


stored as answer

var sessionSchema = mongoose.Schema({
name : String, // the name of the session, like 'SAM' or 'SA'
currQ : Number, // the current question being answered
state : String, // the state of the current question: new, done, asking, summarize
active : Number // 1 if active, 0 otherwise
});


stored as session.

In the ejs file, one function get one answer-tpye variable and use

var reply = JSON.parse(res);


then

session = reply.session._id;


I am really confused what's this line means. There are still many case when _id is used but they didn't define it.

Answer

_id is added to all MongoDB documents by default.

Mongoose also adds an id getter for a string representation of _id so you can also call

reply.session.id

These properties will be available without being explicitly added to the schema