如何在mongoose中添加架构方法? [重复]

时间:2021-07-05 04:24:05

This question already has an answer here:

这个问题在这里已有答案:

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?

我一直试图找出如何在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();
});

1 个解决方案

#1


6  

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

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

With that you can do:

有了它你可以做:

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

#1


6  

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

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

With that you can do:

有了它你可以做:

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