【发布时间】:2013-12-04 23:42:41
【问题描述】:
我在更新 mongoose 文档后无法使用 save()。看起来从 find、findOne 或 findById 传递的类型是 Mongoose 文档而不是模型,因此它缺少 save() 函数。 update() 可用,但它跳过了我需要的中间件。
我能找到的最接近的是: mongoose - 'save' method does not exist 但看起来它仍然将 Document 传递给我,而不是 Model 实例。
这可能是我的版本吗?使用最新的 NPM - 3.8.1
models.StudySubject.findById(id, function (err, studySubject) {
if (err)
return cb(err);
if (!studySubject)
return cb({ status: 404, error: 'Study subject not found'});
var subjectInfo = extractSubjectFields(params);
delete subjectInfo.study; // prevent study change
updateObjOneLevel(studySubject, subjectInfo);
studySubject.save(function (err, studySubject, count) {
if (err)
return cb(err);
if (count !== 1)
return cb({ status: 500, error: 'Error saving Study Subject' });
cb(null, studySubject);
});
});
extractSubjectFields() 查看输入 params 的可选更新字段,例如:
if (params.study)
subjectInfo.study = params.study;
堆栈跟踪:
Uncaught TypeError: Object #<Object> has no method 'save'
at C:\....\node_modules\mongoose\lib\document.js:1270:13
架构:
var studySubjectSchema = new mongoose.Schema({
_id: {
type: String,
default: function() { return uuid.v4() },
match: [/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/, "Invalid UUID"]
},
study: {
type: String,
ref: 'Study',
required: "Study reference is required: `{PATH}` - `{VALUE}`"
},
first_name: {
type: String,
encrypt: true
},
last_name: {
type: String,
encrypt: true
},
date_of_birth: {
type: String,
encrypt: true
},
mrns: [MRNSchema],
metadata: {
type: {},
validation: [function (val) {
return (typeof val == 'object');
}, "Metadata field must be a key/value object"]
},
enrollments: [{
type: String,
match: [/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/, "Invalid Enrollment UUID"],
ref: 'Enrollment'
}]
});
var enrollmentSchema = new mongoose.Schema({
_id: {
type: String,
default: function() { return uuid.v4() },
lowercase: true,
match: [/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/, "Invalid UUID"]
},
study: {
type: String,
ref: 'Study',
required: "Study reference is required: `{PATH}` - `{VALUE}`"
},
first_name: {
type: String,
required: true
},
last_name: {
type: String,
required: true
},
date_of_birth: {
type: String,
required: true
},
mrns: [MRNSchema],
metadata: {
type: {},
validation: [function (val) {
return (typeof val == 'object');
}, "Metadata field must be a key/value object"],
},
consents: [ConsentSchema],
subject_study_code: {
type: String,
index: true
},
unenrolled: {
type: Date
}
});
谢谢!
【问题讨论】:
-
findById为我返回一个模型实例(ctor 名称为model)。莫非updateObjOneLevel()做了什么奇怪的事情? -
我试过评论那个函数,只是手动修改一个属性
studySubject.first_name = 'Barney',但仍然给我一个错误,即 save() 不存在,但 update() 存在并且 document.js 是堆栈跟踪中的文件 -
嗯
console.log(studySubject.save);给我{ [Function] numAsyncPres: 0 } -
堆栈跟踪中提到的代码与看起来像嵌套文档数组的内容有关。听起来您可能正在混合子文档和文档引用?
-
我有点不清楚到底发生了什么,但我猜它与
mrns数组有关。