Mongoose에서 개체를 찾아 저장하는 도우미 메서드를 추가하려면 어떻게해야합니까? 한 친구가 도우미 방법을 사용하라고 말했지만 하루가 지나면 일할 수 없습니다. 난 항상 (노드가 컴파일 할 때 ... 나는 그것을 실행하기 전에) findOne()
또는 save()
중 하나가 존재하지 않거나 그 다음 콜백이 정의되어 있지 않습니다 말하는 오류가 나타납니다, _schema.statics을몽구스 도우미 메서드에는 findOne 메서드가 없습니다?
내가 해봤 _schema.methods을 ... 아무것도 당신이 때문에 this
와 사용의 문제로 실행하는 생각
var email = require('email-addresses'),
mongoose = require('mongoose'),
strings = require('../../utilities/common/strings'),
uuid = require('node-uuid'),
validator = require('validator');
var _schema = new mongoose.Schema({
_id: {
type: String,
trim: true,
lowercase: true,
default: uuid.v4
},
n: { // Name
type: String,
required: true,
trim: true,
lowercase: true,
unique: true,
index: true
}
});
//_schema.index({
// d: 1,
// n: 1
//}, { unique: true });
_schema.pre('save', function (next) {
if (!this.n || strings.isNullOrWhitespace(this.n)){
self.invalidate('n', 'Domain name required but not supplied');
return next(new Error('Domain name required but not supplied'));
}
var a = email.parseOneAddress('[email protected]' + this.n);
if (!a || !a.local || !a.domain){
self.invalidate('n', 'Name is not valid domain name');
return next(new Error('Name is not valid domain name'));
}
next();
});
_schema.statics.validateForSave = function (next) {
if (!this.n || strings.isNullOrWhitespace(this.n)){
return next(new Error('Domain name required but not supplied'));
}
var a = email.parseOneAddress('[email protected]' + this.n);
if (!a || !a.local || !a.domain){
return next(new Error('Name is not valid domain name'));
}
next();
}
_schema.statics.findUnique = function (next) {
this.validateForSave(function(err){
if (err){ return next(err); }
mongoose.model('Domain').findOne({ n: this.n }, next);
//this.findOne({ n: this.n }, next);
});
}
_schema.statics.init = function (next) {
this.findUnique(function(err){
if (err){ return next(err); }
this.save(next);
});
}
var _model = mongoose.model('Domain', _schema);
module.exports = _model;
몽구스가'_id'를 생성하는 대신'_id'를'uuid'로 설정하는 이유가 있습니까? – EmptyArsenal
나는 순차적 또는 거의 순차적 인 ID를 원하지 않기 때문에. –
@ G.Deward : 죄송합니다. 나는 노력했다. 조건에 따르면, 내가 편집 한 경우에만 현상금을 할당 할 수 있습니다. 불행히도, 두 명의 동료가 그것을 (@bulk과 @dleh) 거부했다. 그들은 용어가 지정하지 않은 것을 알고 있거나 내 주석을 읽지 않았다. http://stackoverflow.com/help/bounty –