如何解决猫鼬在数组中添加子文档,给出错误_id:this.ownerDocument...model不是函数
我有两种模式:
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const _ = require("lodash");
const { regex } = require("../config/constants");
const { schemaErrors } = require("../config/errors");
const SiaSchema = require("./SiaModel");
const EmployeeSchema = new Schema(
{
first_name: {
type: String,required: true,trim: true,},last_name: {
type: String,mobile: {
type: String,validate: {
validator: function (v) {
return regex.uk.mobile.test(v);
},message: schemaErrors.INVALID_MOBILE,sia: [SiaSchema],{ timestamps: { createdAt: "created_at",updatedAt: "updated_at" } }
);
EmployeeSchema.statics.addSia = async function (data) {
let options = { new: true,upsert: true,runValidators: true };
let sia = Object.assign({},data);
delete sia._id;
let orQuery = [];
for (const attribute in sia) {
orQuery.push({ [`sia.${attribute}`]: sia[attribute] });
}
let existing = await this.findOne({ $or: orQuery });
if (existing) return Promise.resolve(existing);
return this.findByIdAndUpdate(data._id,{ $push: { sia: sia } },options);
};
module.exports = EmployeeSchema; // I am not exporting mongoose model here because model creation for all schemas is being handled by another module
和
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const _ = require("lodash");
const { regex } = require("../config/constants");
const { schemaErrors } = require("../config/errors");
const SiaSchema = new Schema(
{
sia_number: {
type: String,validate: {
validator: function (v) {
return regex.uk.sia.test(v);
},message: schemaErrors.INVALID_SIA_NUMBER,issue_date: {
type: Date,validate: {
validator: function (v) {
return v instanceof Date && v.getTime() < Date.now();
},message: schemaErrors.INVALID_ISSUE_DATE,expiration_date: {
type: Date,validate: {
validator: function (v) {
return v instanceof Date && v > this.issue_date;
},message: schemaErrors.INVALID_EXPIRATION_DATE,updatedAt: "updated_at" } }
);
module.exports = SiaSchema; // I am not exporting mongoose model here because model creation for all schemas is being handled by another module
我创建了 Employee 。然后,我调用了另一个API,以使用 Employee Schema 中定义的 addSia 静态方法为该员工添加Sia,但这给了我以下错误:
"Validation failed: sia: Validation failed: _id: this.ownerDocument(...).model is not a function".
这是API的主体,数据作为data
参数传递给addSia方法:
{
"_id": "5f36cde0e4c4163838674219",// ID of the employee for whom I want to add sia
"sia_number": "0000000000000000","issue_date": "2020-08-01","expiration_date": "2025-08-01"
}
如果我在addSia方法中从runValidators: true
中删除了options
,则该函数有效,但未应用验证。
在此方面的任何帮助,我将不胜感激。
Node.js版本11.9.0
猫鼬版本5.9.28
Mongodb版本4.2.3
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。