首页 文章

mongoose:更新字段,在数组中推送对象[复制]

提问于
浏览
0

这个问题在这里已有答案:

我想在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来自哪里?我怎么能摆脱它?

更新:mongoose架构:

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
});

1 回答

  • 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
    });
    

相关问题