【问题标题】:Nested Arrays in Mongoose with ObjectId在 Mongoose 中使用 ObjectId 嵌套数组
【发布时间】:2013-06-17 19:13:26
【问题描述】:

我正在尝试记录用户投票的帖子的 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")
            }
        ]
    }

我对 mongoose 在 votedPosts 数组中添加的额外“_id”感到困惑。为什么 ObjectId("51bf5e48c3ffefe20c000002") 不能成为键值对的键?

【问题讨论】:

    标签: javascript node.js mongodb mongoose


    【解决方案1】:

    我认为您的问题源于您的架构。您应该尝试定义一个键不会动态变化的模式。 MongoDB 不支持对文档键的查询,只支持对值的查询。

    我认为在上述架构中使用动态“ObjectID”作为键会导致 Mongoose 变得奇怪,并导致您的问题。但是,即使您的查询已正确传播到 MongoDB,它仍然不会产生您想要的输出。这样做的原因是 MongoDB 将“postID”解释为字符串,无论您是否定义了一些 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"
                }
            }
        ]
    }
    

    我建议您使用其他架构。我在下面提出的架构涉及embedding a second schema into your existing schema。试试这样的:

    var votedPost = new Schema({
        postID: ObjectId,
        votetype : Number 
      });
    
    var userSchema = new Schema({
        twittername: String,
        twitterID: Number,
        votedPosts: [votedPost]
      });
    

    这样,您还可以查询 MongoDB 处理得非常好的 postID 字段。那有意义吗? :)

    【讨论】:

      猜你喜欢
      • 2022-01-15
      • 2014-11-05
      • 2021-04-01
      • 2012-05-21
      • 2021-03-03
      • 2018-06-07
      • 2016-05-03
      • 2012-07-05
      • 2021-11-04
      相关资源
      最近更新 更多