1

I'm unclear about the new keyword in node.js. I know it basically create an instance of my schema. But why I don't need to declare new when I do an update? so my question is when to use new here.

var User = module.exports = mongoose.model('tokens', userSchema);
//route endpoint here
..
new User({user: user_id, data: data}).save(callback);

If I don't use new in above code what will happens? the flow of the code make sense even if I don't. Correct me if I'm wrong, thanks.

Alicia Brandon
  • 485
  • 1
  • 5
  • 12
  • Read [this](http://stackoverflow.com/a/3658673/2607571) for a introduction to new. I have no idea if in this case new is neccessary and what it actually does. (But I suspect something related to inheritance) – Simon Kirsten Jun 12 '16 at 00:56

2 Answers2

1

I know it basically create an instance of my schema.

Actually, in your first line of code you are creating the model, which uses the schema (is not an instance). In your last line you are creating an instance of the model you first created (which is called a document).

But why I don't need to declare new when I do an update?

You don't necessarily have to use new every time you make DB calls, but there are some benefits to it (see the last link)

If I don't use new in above code what will happens?

The same thing will happen.

so my question is when to use new here.

A good answer to your question. I choose to create a document when I actually create a row in the database (that is, when I create a new user). For searches (for ex.) (findOne, findById) I use the model. This helps me keep my code semantically separate.

Community
  • 1
  • 1
ali404
  • 1,143
  • 7
  • 13
  • the same thing will happends? then what's the point of `new` in above case? it doesn't have to validate anything (according to the link you gave). – Alicia Brandon Jun 13 '16 at 15:49
0

new keyword is needed in case if you need to create a new entity.

Let's say you want to create a new user in your DB. You can do it like this: const user = new User({user: id, data}) Then you have two options, you can mutate the user object before saving or save it immediately using user.save().

Like this:

const user = new User({user: id, data})
user.age = 21;
user.save();

In your practice you will notice that sometimes you don't want to save entity in DB when it is created. Sometimes before inserting into DB you want to perform some manipulations with it.

Regarding question why you don't need to use new keyword before you perform update.

So to perform update, first you need to retrieve existing document from DB. User.find({id: 'someid'}); In this case Mongoose will generate a new object for you. User.find will return you a new object. Which is able to be updated, due to it is already in DB.

Dmitrijs Balcers
  • 160
  • 1
  • 12