代码之家  ›  专栏  ›  技术社区  ›  Egidi

Mongoose-更新文档,添加新密钥(具有strict:false)

  •  2
  • Egidi  · 技术社区  · 10 年前

    我有以下猫鼬模型:

    var mongoose = require('mongoose');
    var Schema = mongoose.Schema;
    
    var companySchema = new mongoose.Schema({
        name: String, 
        long_name: String,
        address: String,
        telephone: String,
        mobile_phone: String,
        fax: String,
        email: String,
        url: String,
        config:{
            language: String,
            account: String
        },
        items:[{
            name: String,
            internal_id: String,
            reference_code: String,
            description: String
        }]
    },{ timestamps: true, strict: false });
    
    var Company = mongoose.model('Company', companySchema);
    
    module.exports = Company;
    

    好的,想法是让每个用户在items数组中插入自己的字段。例如,用户将创建一个带有几个新键/值对的新项。我将在项目数组中存储新项目:

    var Company = require('mongoose').model('Company');
    
    exports.createItem = function(req, res, next) {
    
            var newitem = {
                "name": "Syringe Needels",
                "internal_id": "ID00051",
                "reference_code": "9506",
                "description": "My description",
                "batch": "100",
                "room": "240",
                "barcode": "9201548121136"
            };
    
    
          Company.findById(req.company, function(error, company) {
               company.items.push(newitem);
               company.save(function(err, doc){
                return res.status(200).send('The new item has been stored!');
              });
    
          });
    };
    

    未在架构中定义的键未被存储;只存储名称、内部id、引用代码和描述。

    我如何才能做到这一点?

    1 回复  |  直到 10 年前
        1
  •  2
  •   Taha    10 年前

    您可以创建数据类型为混合对象的子文档。这将允许您动态插入/更新密钥

    var companySchema = new mongoose.Schema ({
        name: String, 
        long_name: String,
        address: String,
        telephone: String,
        mobile_phone: String,
        otherProps : {}
    })
    

    此(otherProps键)将完成任务