根据mongoose文档,有3种方法可以在文档中添加自定义方法:
1.通过架构选项
1.直接将“方法”对象分配给模式
1.使用Schema.method()帮助器
然而,经过多次尝试,我只设法让方法使用选项1工作。我很好奇为什么选项2和3不为我工作。以下是我的代码:
app.js
socket.on("message", async function (clusterData, callback) {
console.log("socket event fired");
const parentCluster = await Message.findById(clusterData.clusterId);
coonsole.log(parentCluster); // exists as expected
parentCluster.optionsMethod(); // log : "options method called" ✔
parentCluster.objectMethod(); // error : parentCluster.objectMethod is not a function ❌
parentCluster.helperMethod(); // error : parentCluster.helperMethod is not a function ❌
});
Message.js
import mongoose from "mongoose";
const messageSchema = new mongoose.Schema({
mentions: [{ type: mongoose.Schema.Types.ObjectId, ref: "User" }],
text: { type: String, trim: true },
file: { type: String },
dateString: { type: String, required: true },
timestamp: { type: Number, required: true },
});
const messageClusterSchema = new mongoose.Schema(
{
sender: {
type: mongoose.Schema.Types.ObjectId,
ref: "User",
required: true,
},
channel: {
type: mongoose.Schema.Types.ObjectId,
ref: "Channel",
required: true,
},
group: {
type: mongoose.Schema.Types.ObjectId,
ref: "Group",
required: true,
},
content: [messageSchema],
clusterTimestamp: {
type: Number,
required: true,
},
},
{
toObject: { virtuals: true },
toJSON: { virtuals: true },
methods: {
optionsMethod() {
console.log("options method called");
},
},
}
);
messageClusterSchema.virtual("lastMessage").get(function () {
return this.content[this.content.length - 1];
});
messageClusterSchema.pre("validate", function () {
console.log("pre validate ran");
this.clusterTimestamp = this.content[this.content.length - 1].timestamp;
});
// assign directly to object
messageSchema.methods.objectMethod = function () {
console.log("object method called");
};
// assign with helper
messageSchema.method("helperMethod", function () {
console.log("helper method called");
});
console.log(messageSchema.methods); // {objectMethod: [Function (anonymous)], helperMethod: [Function (anonymous)]}
console.log(messageSchema.methodOptions); // { helperMethod: undefined }
const Message = mongoose.model("Message", messageClusterSchema);
export default Message;
1条答案
按热度按时间jv4diomz1#
问题是,
objectMethod
和helperMethod
位于messageSchema
和Message.js文件中,您正在创建messageClusterSchema
的模型,您正在socket函数中导入和使用该模型。这两个方法都只能通过messageSchema
的模型示例调用。这就是optionsMethod
调用的原因,但另外两个不是。基本上你需要创建messageSchema
的模型,并导出它以便在其他文件中使用。简而言之,错误在于:
该模型是使用
messageClusterSchema
生成的,但方法被分配给messageSchema
:应将它们分配给
messageClusterSchema
。