在我的代码中,我有以下模型。
const PostSchema = new mongoose.Schema ( {
title: String,
owner: String,
creationDate: Date,
editionDate: Date,
tags: [String],
score: Number,
votes:
[
{
user: String,
type: Boolean
}
],
text: String
} );
我在发布控制器中有以下方法。
async store (request, response)
{
const {title = "", owner = "", tags = [], text = ""} = request.body;
var creationDate = new Date ();
var offset = creationDate.getTimezoneOffset ();
var minutes = creationDate.getMinutes ();
creationDate.setMinutes (minutes-offset);
const newPost = await Post.create ({title, owner, creationDate, editionDate: null, tags, score: 0, votes: [], text});
return response.json (newPost);
}
如果我尝试使用votes: [{user: "", type: true}]
而不是votes: []
,则会出现以下错误。
UnhandledPromiseRejectionWarning: ValidationError: Post validation failed: votes.0: Cast to Boolean failed for value "{ user: '', type: true }" at path "votes", votes: Cast to Array failed for value "[ { user: '', type: true } ]" at path "votes"
如果我使用votes: [true]
,则不会发生任何错误,并且创建的对象的投票数组中包含true
。
如果我尝试使用更新方法将{user: "", type: true}
推入阵列,则会发生相同的错误。
这是怎么回事?
答案 0 :(得分:0)
嘿,您尝试将默认值设置为票数,因此,如果用户未插入值,则默认情况下该值为false或true。
Votes: [
{
user: String,
type: Boolean,
default: true
}
]