简体   繁体   中英

nodejs mongo prototype best practices

I'm new in the node.js world, but I'm trying to do a REST API with mongoDB and some javascript prototyping.
What is the best approach to have a model and the prototype object? Do i need to have the mongo schema definition in the same class of the prototype?

For example:

var Person = function (name) {
     this.name = name; 
}

Person.prototype.getSchema  = function () {   //To-do create mongo schema
}

Person.prototype.getName = function () {
    return this.name;
}

Is that a good approach? Do I have to modify something?

I recommend to you starting with mongoose. In mongoose would be something like this:

const mongoose = require('mongoose')
const Schema = mongoose.Schema

var userSchema = new Schema({
  username: String,
  password: String
})

userSchema.statics = {
  getByName(name) {
    return this.find({name})
      .exec(function(err, user) {
        console.log(user);
    });
  }
}

module.exports = mongoose.model('User', userSchema)

Then in your controller you can import the User model and use the model method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM