我正在尝试使用Mongoose创建一个应用程序接口,并且我有一个模型,在这个模型中我想要自动递增postID的值。我有post模式
const PostSchema = new Schema({
title: {
type: String,
required: true
},
postID: {
type: Number,
unique: true,
required: true
},
body: {
type: String,
required: true
},
author: {
type: Schema.Types.ObjectId,
ref: 'Author',
required: true
},
dateCreated: {
type: Date,
required: true
},
lastModified: {
type: Date,
required: false
},
modifiedBy: {
type: Schema.Types.ObjectId,
ref: 'Author',
required: false
},
picture: {
type: mongoose.SchemaTypes.Url,
required: false
}
}, {collection: 'Post'});我已经创建了一个保存前的钩子
export const PostModel = mongoose.model('Post', PostSchema);
PostSchema.pre('save', true, async function (next) {
const post = this;
post._id = new ObjectID();
post.dateCreated = new Date();
try {
const lastPost = await PostModel.find({postID: {$exists: true}}).sort({id: -1}).limit(1);
post.postID = lastPost.postID + 1;
} catch (e){
console.log('could not take the last post')
}
if(post && post.hasOwnProperty('body') && !post.body.isModified){
return next();
}
if(post && post.hasOwnProperty('body') && post.body.isModified){
post.lastModified = new Date();
return next();
}
});来处理添加创建日期和自动递增postID。然而,每当我向API发送一个突变来创建新的post时,我得到一个错误,Post validation failed: dateCreated: Path dateCreated is required., id: Path id is required.,这意味着在pre-save钩子中处理的任何工作都没有完成。每当我向解析器添加一些随机值时,变异都会成功完成。你知道为什么预存不起作用吗?
这是我的解析器
module.exports.addPost = async(_,args, req) => {
const post = new PostModel({
title: args.post.title,
body: args.post.body,
author: new ObjectID(args.post.author),
picture: args.post.picture
});
try {
return await post.save();
} catch (e) {
console.log('Could not save the post');
console.log(e);
}
};而这里的变异
curl 'http://localhost:3001/graphql' -H 'Accept-Encoding: gzip, deflate, br' -H 'Content-Type: application/json' -H 'Accept: application/json' -H 'Connection: keep-alive' -H 'DNT: 1' -H 'Origin: http://localhost:3001' --data-binary '{"query":"mutation($post: PostInput){\n addPost(post: $post){\n title\n body\n author\n }\n}","variables":{"post":{"title":"newTitle","body":"Lorem ipsum","author":"5e07e6c07156cb000092ab45","picture":"http://www.example.com"}}}' --compressed发布于 2019-12-29 23:19:37
上面的代码片段将不起作用。根据Mongoose的文档,在编译模型后调用pre或post挂钩不起作用。所以你应该搬走
export const PostModel = mongoose.model('Post', PostSchema);带上前钩。此外,由于PostModel尚未定义,并且您希望获取插入到数据库中的对象的最后一个id,因此可以将此检查转移到您的解析器。
let lastPost = await PostModel.find({id: {$exists: true}}).sort({id: -1}).limit(1);
// This always returns an array, either empty or with data
if(Array.isArray(lastPost) && lastPost.length > 0){
lastPost = lastPost[0]
}
const post = new PostModel({
...
id: lastPost['id'] + 1
...
});
if(Array.isArray(lastPost) && lastPost.length === 0) {
post.id = 0;
// If this lastPost is an empty array and you try to access the id property
// you will get an error that NaN to Int conversion failed
}希望这能有所帮助
https://stackoverflow.com/questions/59516237
复制相似问题