How to instantiate an object to create a document in mongodb

0

Hi, I'm new to this, I understand that to create the model of a scheme, it's like that = >

var Movie = mongoose.model('Movie', movieSchema);

  var movie      = new Movie(); //instanciamos mi objeto user(Documents are instances of our model)
movie.name     = 'admin1';
movie.email    = '[email protected]';
movie.password = 'Berna123';
movie.age      = 28;

But of course I want to do it like this but it does not leave me since it says that Movie is already defined, I would like to then insert movies randomly with a loop, how can I do it? = >

class Movie{
Constructor(name, email, password, age){
  this._name = name;
  this._email = email;
  this._password = password;
  this._age = age;
}

}

var movieName = new Movie ('Harry Potter', '[email protected]', 'Berna123', 28);

'use strict';

//1. Dependencies & Connecting
var mongoose = require('mongoose');

var mongoosePaginate = require('mongoose-paginate');

mongoose.connect("mongodb://localhost/peliculas-random", function(err){
    if (err) console.log('error');
    else console.log('connection has been made');
});

//2. General Schema
var Schema = mongoose.Schema;

//3. Movie Schema
var movieSchema = new Schema({
    name:{type:String, required:true, unique: false},
    lastname:{type:String},
    email:{type:String},
    password:{type:String},
    age:{type:Number},
});

//Mongoose Paginate
movieSchema.plugin(mongoosePaginate);

//4. Constructor of my Schema
var Movie = mongoose.model('Movie', movieSchema);

//5. Populating Collection
function createMovie(){

    var movie      = new Movie(); //instanciamos mi objeto user(Documents are instances of our model)
    movie.name     = 'admin1';
    movie.email    = '[email protected]';
    movie.password = 'Berna123';
    movie.age      = 28;

    movie.save(function(err){ // Sving instance of my model
        if (err) console.log('There is an error: ' + err.message);
        else console.log('Movie created successfully');
    });
    console.log(movie);
}
createMovie();

// class Movie{
//     Constructor(name, email, password, age){
//       this._name = name;
//       this._email = email;
//       this._password = password;
//       this._age = age;
//     }
// }
//
// var movieName = new Movie('Harry Potter', '[email protected]', 'Berna123', 28);
//
//
// mongoose.connection.close();
    
asked by francisco dwq 10.04.2018 в 13:29
source

1 answer

1

In order to create an instance of your model, you have to send it an object with the parameters that it requires, in the case of your Movie entity it would be something like this:

var movie = new Movie({
    name: 'admin1',
    email: '[email protected]',
    password: 'Berna123',
    age: 28    
})

This way you should not have problems creating multiple instances using a loop, you will only have to do your movie.save() in each iteration of your cycle.

    
answered by 10.04.2018 в 16:12