微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

node.js – 如何在mongoose中添加模式方法?

参见英文答案 > Virtuals vs Methods in Mongoose1个
我一直试图找出如何在Mongoose中添加模式方法,它将使用模型属性并以某种方式修改它们.是否可以使下面的代码工作?
var mySchema = new Schema({
  name: {
    type: String
  },createdAt: {
    type: Date,default: Date.Now
  },changedname: function () {
    return this.name + 'TROLOLO';
  }
});
MySchema.findOne({ _id: id }).exec(function (error,myschema) {
   myschema.changedname();
});

解决方法

我想是的,你想要实例方法吗?那是你用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);

有了这个你可以做:

Something.findOne({ _id: id }).exec(function (error,something) {
   something.changedname();
});

原文地址:https://www.jb51.cc/nodejs/241235.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐