【问题标题】:mongoose: update field, push object in array [duplicate]猫鼬:更新字段,将对象推送到数组中[重复]
【发布时间】:2016-02-28 19:17:24
【问题描述】:

我想在 mongo 数据库的数组中添加一个元素:

db.keypairs.update( {pubkey: "1234567890"}, { $push: {listTxId: {txHash: "yyy", spent: false} } } )

结果很完美:

listTxId" : [ { "txHash" : "xxx", "spent" : true },{ "txHash" : "yyy", "spent" : false } ]

现在我想对 node.js 和 mongoose 做同样的事情

var res = wait.forMethod(Keypair,'update', {pubkey: "1234567890"}, { $push: { "listTxId": {"txHash":"zzz", "spent":false} } } );

Keypair 是我的 mongoose 集合的 node.js 模型:

var Keypair = require('./app/models/Keypair');

而wait.forMethod来自一个节点模块:

var wait = require('wait.for');

结果,我有这个“_id”元素:

{ "txHash" : "zzz", "spent" : false, "_id" : ObjectId("56561571fea5d9a10a5771fd") }

问题:这个 ObjectId 来自哪里?我怎样才能摆脱它?

更新:猫鼬模式:

var keypairSchema = mongoose.Schema({
    userId      : { type: mongoose.Schema.Types.ObjectId, ref: 'User' },
    pubkey      : String,
    privkeyWIF  : String, // temp
    balance     : Number,
    listTxId    : [{
        txHash : String,
        spent  : Boolean
     }],
    walletId    : { type: mongoose.Schema.Types.ObjectId, ref: 'Wallet' },
    description : { type: String, maxlength: 40 },
    comments    : String,
    isMasterKey : { type: Boolean, default: false },
    date        : Date
});

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    Mongoose 会将 id 放入您的子文档数组中。 listTxId 是一个子文档数组。您可以将 _id: false 添加到您的架构中以防止这种情况发生:

    var keypairSchema = mongoose.Schema({
        userId      : { type: mongoose.Schema.Types.ObjectId, ref: 'User' },
        pubkey      : String,
        privkeyWIF  : String, // temp
        balance     : Number,
        listTxId    : [{
            _id: false,
            txHash : String,
            spent  : Boolean
         }],
        walletId    : { type: mongoose.Schema.Types.ObjectId, ref: 'Wallet' },
        description : { type: String, maxlength: 40 },
        comments    : String,
        isMasterKey : { type: Boolean, default: false },
        date        : Date
    });
    

    【讨论】:

      猜你喜欢
      • 2019-09-14
      • 2017-10-03
      • 1970-01-01
      • 1970-01-01
      • 2016-05-25
      • 2021-02-09
      • 2019-10-13
      • 2019-03-22
      相关资源
      最近更新 更多