[英]Mongoose nested ObjectId Array validation Dto
[英]Nested Arrays in Mongoose with ObjectId
我正在嘗試記錄用戶已投票的帖子的ID,並且正在為它創建一個架構,如下所示:
var userSchema = new Schema({
twittername: String,
twitterID: Number,
votedPosts: [{ObjectId : {votetype : Number}} ]
});
用戶得到了完美的創建,並且每當用戶對某項投票時,我都想更新votedPosts屬性,因此我致電:
User.update({twitterID : req.body.userID} , { $push : {votedPosts : {postID : {votetype: newvotetype }}}} ,function (err, user, raw) {
if (err){
console.log(err);
}
else{
console.log('user ' + user);
}
});
不幸的是結果不是我在架構中所描述的,我得到了:
db.users.find().pretty()
{
"__v" : 0,
"_id" : ObjectId("51bf4ef8dbda2f2e0c000001"),
"twitterID" : 102016704,
"twittername" : "gorkemyurt",
"votedPosts" : [
{
"_id" : ObjectId("51bf5e48c3ffefe20c000002")
}
]
}
貓鼬在投票的數組中添加了額外的“ _id”,這讓我感到困惑。為什么ObjectId(“ 51bf5e48c3ffefe20c000002”)不能成為鍵值對的鍵?
我認為您的問題源於您的架構。 您應該嘗試定義一個架構,在其中密鑰不會動態更改。 MongoDB不支持對文檔鍵的查詢,僅支持值。
我認為在上面的模式中使用動態的“ ObjectID”作為鍵會導致貓鼬怪異,並引起您的問題。 但是,即使您的查詢已正確傳播到MongoDB,它仍然不會產生您想要的輸出。 這樣做的原因是,無論您是否已定義一些postID變量來保存動態值,MongoDB都會將“ postID”解釋為字符串。 如果您使用變量postID從mongo shell運行查詢,則輸出為:
> var postID = 1234
> db.users.update( {twitterID : 102016704}, {$push : {votedPosts : {postID : {votetype: "newvotetype" }}}} )
{
"__v" : 0,
"_id" : ObjectId("51bf4ef8dbda2f2e0c000001"),
"twitterID" : 102016704,
"twittername" : "gorkemyurt",
"votedPosts" : [
{
"postID" : {
"votetype" : "newvotetype"
}
}
]
}
我建議您使用其他架構。 我在下面提出的模式涉及將第二個模式嵌入到您現有的模式中 。 嘗試這樣的事情:
var votedPost = new Schema({
postID: ObjectId,
votetype : Number
});
var userSchema = new Schema({
twittername: String,
twitterID: Number,
votedPosts: [votedPost]
});
這樣,您還可以查詢MongoDB很好處理的postID字段。 那有意義嗎? :)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.