如何在猫鼬中添加模式方法? [英] How to add schema method in mongoose?

查看:47
本文介绍了如何在猫鼬中添加模式方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've been trying to find out how to add schema methods in Mongoose which will use model attributes and modify them in some way. Is it possible to make the code below work?

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 方法的意思吗?如果是这样,您可以执行以下操作:

I think so, did you want instance methods? Is that what you meant with Schema methods? If so, you can do something like:

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();
});

这篇关于如何在猫鼬中添加模式方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆