Reputation: 1199
I'm trying to use mongoose statics, so I followed the docs and so far not working as expected. I have tried a lot of ways to export/import the model. Every time I see a different error, once the functions I made weren't defined on the model and others type error.
this is my model:
const mongoose = require("mongoose");
const Schema = require("../../config/DB").Schema;
const db = require("../../config/DB").db;
//schema
const MessagesSchema = new Schema({
userID: { type: Number, required: true },
messageText: { type: String, required: true }
});
MessagesSchema.statics.saveMessage = function(MessageData, cb) {
this.insertOne(MessageData, (err, result) => {
if (err) {
console.log(err);
cb(err, null);
} else {
cb(null, result);
}
});
};
MessagesSchema.statics.findMessages = function(userID, cb) {
this.find({}).toArray((err, result) => {
if (err) {
cb(err, null);
} else {
cb(null, result);
}
});
};
module.exports = mongoose.model("Messages", MessagesSchema);
And this is how I used it in another file:
const MessagesModel = require("../../api/models/messages");
MessagesModel.saveMessage(
{ userID: message.sender.id, messageText: message.text },
(err, result) => {
if (err) {
console.log(err);
} else {
console.log(`result object length = ${Object.keys(result).length}`);
}
}
);
Upvotes: 1
Views: 114
Reputation: 7080
A Mongoose model doesn't have an insertOne
method. Use the create method instead:
this.create(MessageData, (err, result) => {
Upvotes: 1