【问题标题】:Is there way to add array of objectid and other field in mongodb schema?有没有办法在 mongodb 模式中添加 objectid 和其他字段的数组?
【发布时间】:2022-01-25 19:05:56
【问题描述】:

我想创建一个模式,具有多个对象 id,每个对象 id 都包含一个数字。

喜欢这个数据,

[ "user": [["collection1",1], ["collection2", 3], ["collection4": 4]

其中user是用户对象id,collection1, collection2 ....是集合对象id,其他都是数字。

const derivedSchema = new mongoose.Schema(
  {
    user: {type: ObjectId, ref: "User"},
    collections: {type: [ObjectId], ref="collection"}],
);

如果看起来像我的数据,我尝试像 put [ObjectId, Number] 一样进行更改

并尝试像这样保存

let collected = new derivedSchema({
        "user": uid,
        "collections": [cid, 12],
      })
      collected.save()

其中cid是collectionid,uid是userid,12个数字,我在for循环中通过了。

但它不起作用。 有没有办法解决这个问题? 谢谢

最终的结果应该是这样的

[
   "user1": { ["col1",1], ["col2", 5]},
   "user2": { ["col1",55], ["col2", 35]},
]
  

有什么想法真的有用吗?

【问题讨论】:

    标签: javascript mongodb mongoose


    【解决方案1】:
    var mongoose = require('mongoose');
    var Schema=mongoose.Schema;
    
    const derivedSchema = new mongoose.Schema(
      {
        user: {
               type: Schema.Types.ObjectId,
               ref: "User"
        },
        collections:{
            type:[Schema.Types.ObjectId],
            ref:"collection"
        }
    );
    

    【讨论】:

    • 您好,谢谢您,这解决了我的问题。如果我想添加喜欢的收藏和编号到那个特定的收藏,我怎么能在那个特定的收藏字段上添加数字。例如像 [userid, [collectionid1, number1], [collectionid2, number5], [collectionid3,number2]]
    猜你喜欢
    • 2012-12-19
    • 1970-01-01
    • 1970-01-01
    • 2020-05-15
    • 1970-01-01
    • 1970-01-01
    • 2021-08-02
    • 2021-10-17
    • 1970-01-01
    相关资源
    最近更新 更多