如何在mongoose中添加schema方法?

pro*_*ype 6 mongoose mongodb node.js

我一直试图找出如何在Mongoose中添加模式方法,它将使用模型属性并以某种方式修改它们.是否可以使下面的代码工作?

var mySchema = new Schema({
  name: {
    type: String
  },
  createdAt: {
    type: Date, 
    default: Date.now
  },
  changedName: function () {
    return this.name + 'TROLOLO';
  }
});
Run Code Online (Sandbox Code Playgroud)

 

MySchema.findOne({ _id: id }).exec(function (error, myschema) {
   myschema.changedName();
});
Run Code Online (Sandbox Code Playgroud)

Dan*_*ego 7

我想是的,你想要实例方法吗?那是你用Schema方法的意思吗?如果是这样,您可以执行以下操作:

var mySchema = new Schema({
      name: {
      type: String
},
   createdAt: {
   type: Date, 
   default: Date.now
}
});

mySchema.methods.changedName = function() {
    return this.name + 'TROLOLO';
};

Something = mongoose.model('Something', mySchema);
Run Code Online (Sandbox Code Playgroud)

有了这个你可以做:

Something.findOne({ _id: id }).exec(function (error, something) {
   something.changedName();
});
Run Code Online (Sandbox Code Playgroud)