【问题标题】:Which type to store an Array of MongoDB ObjectIds?哪种类型存储 MongoDB ObjectIds 数组?
【发布时间】:2016-10-14 19:32:34
【问题描述】:

我想将通过 REST 接口通过 mongoose 获得的 ObjectId 数组保存到 mongodb。我经常遇到将objectIds从REST接口保存到数据库时出现转换错误的问题。服务器端代码是用 typescript 编写的。

架构是:

var WaSchema = new mongoose.Schema({
    ownerId: { type: 'String', required: true },
    options: { type: 'String', required: false },
    launch:  [{ type : 'ObjectId', required: true }],
});

从 REST 接口中,我得到一个“lanch”字符串数组:launch: Array<string>

这是我目前的保存方式:

WaModel.findOneAndUpdate(query, {
            ownerId: userId,
            options: wa.options,
            launch: wa.launch
        },
        { upsert: true },
        (err, doc) => {
            if (err) throw err
            else return 'successfully saved/updated';
        })
  1. REST 接口中的 ObjectId 必须如何看起来才能正确转换?它只是像'575e52790c0fc76a11e381d0'这样的刺痛还是需要像ObjectId(“575e52790c0fc76a11e381d0”)这样的前缀?

  2. 数组最后会是什么样子?这取决于#1的答案

  3. 我看到了填充功能,这对这里有帮助吗?

【问题讨论】:

    标签: node.js mongodb mongoose typescript mongoose-populate


    【解决方案1】:

    1) 如果您使用的是猫鼬,则无需添加前缀 ObjectId。您可以保存为引用 ID 数组。

    var insertData = {
                ownerId: userId,
                options: wa.options,
                launch:  [ '56cea954d82cd11004ee67b5','56ceaa00d82cd11004ee67bc' ]
               }
    

    2) 最后,您的数组将如下所示。

    "launch" : [ 
            ObjectId("56cea954d82cd11004ee67b5"), 
            ObjectId("56ceaa00d82cd11004ee67bc")            
        ],
    

    3) 是的,填充功能在这里会有所帮助。它将填充整个数组。填充后它看起来像

    "launch" : [ 
                 { _id: '56cea954d82cd11004ee67b5',
                   .... other fields
                 },
                 { _id: '56ceaa00d82cd11004ee67bc',
                  .... other fields
                 },
              ]
    

    【讨论】:

      【解决方案2】:

      我会说将对象 ID 存储在数据类型为 ObjectId 的数组中。为此,您应该将字符串格式的 id 转换为 '575e52790c0fc76a11e381d0' 类型为 ObjectId

      使用以下方法进行转换:

      考虑到 id 是a user (userId)

      var stringUserId = '575e52790c0fc76a11e381d0';
      var ObjectId = mongoose.Types.ObjectId;
      var userId = ObjectId(stringUserId); //This should assign a value of datatype ObjectId to userId
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-11-13
        • 2016-11-23
        • 2012-01-09
        • 2020-06-30
        • 2011-09-06
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多