【问题标题】:Add to array in Mongoose schema添加到 Mongoose 模式中的数组
【发布时间】:2015-04-08 19:09:04
【问题描述】:

我有一个类似于以下示例的猫鼬模式模型。帐户字段是一个帐户 ID 数组。

var ListingSchema = new Schema({
  listing: { type: String, required: true },
  admin: { type: String, required: true, index: true },
  accounts: [{ type: String, index: true }]
});

现在在我的 Node/Express 后端中,我添加了一个类似这样的条目:

Listing.create({
  listing: req.body.id,
  admin: req.session.userID,
  account: req.session.userID
}, function (err){ 
  if (err) throw err;
  else res.send({success:true});
});

但是我没有正确添加到帐户字段,因为它是一个数组。我该怎么做?

【问题讨论】:

    标签: node.js mongoose


    【解决方案1】:

    创建试试这个:

    var accounts = [req.session.userID];
    
    Listing.create({
      listing: req.body.id,
      admin: req.session.userID,
      accounts: accounts 
    }, function (err){ 
      if (err) throw err;
      else res.send({success:true});
    });
    

    要更新,试试这个:

    { $push: { accounts: 'value' }
    

    【讨论】:

      【解决方案2】:
      var accounts = [req.session.userID];
      

      还有

      accounts: [{ type: String, index: true }]
      

      应该是

      accounts: [{ type: Array, index: true }]
      

      【讨论】:

        猜你喜欢
        • 2016-03-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-03-24
        • 2014-12-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多