猫鼬:从“混合类型”中查找子文档并进行更新

时间:2018-07-10 05:42:47

标签: mongodb mongoose

我要更新和删除子文档。文档的结构如下,

   {
  "projectId": "12345-service-request",
  "projectVersion": [{
    "version":"1",
    "localConfig": [{
      "port": "3003",
      "mongoURI": "mongodb://localhost:27017/serviceRequest",
      "MQ": "RMQ",
      "logLevel": "2",
      "version": "1.1",
      "created": "03-06-2018 03:11:00 PM",
      "active": "N"
    },
    {
      "port": "3004",
      "mongoURI": "mongodb://localhost:27017/serviceRequest",
      "MQ": "IMQ",
      "logLevel": "1",
      "version": "1.2",
      "created": "07-06-2018 03:11:00 PM",
      "active": "Y"
    }]    
  }]
}

“ localConfig” 中的字段不同,它们随项目而不同。 因此,我使用 Schema.Types.Mixed 为此创建了架构,如下所示,

const mongoose = require('mongoose');
mongoose.set('debug', true);
const Schema = mongoose.Schema;

const projectVersion = new Schema({ 
    version: {type:String, required: true},
    cloudParams: [String],
    localConfig: [{type:Schema.Types.Mixed}]    // Mixed Type schema
});

const projectConfig = new Schema({
    projectId : {type:String, required: true},
    projectVersion : [projectVersion]
});

module.exports = mongoose.model("ProjectConfig", projectConfig);

现在,我正在尝试使用条件查找子文档

projectId = 12345-service-request and
projectVersion.localConfig.version = 1.2

但是返回完整的文件。 使用$ and $elemMatch

查找子文档的代码
    let projectId = '12345-service-request';
    let version = '1.2'
    // Using $
    ProjectConfig.findOne({'projectId' : projectId,'projectVersion.localConfig.version' : version },
        { 'projectVersion.$' : 1 }).exec(function(err,projectConfig){
console.log("Result : "+JSON.stringify(projectConfig)); 
        }); 

ProjectConfig.find({'projectId' : projectId,'projectVersion.localConfig.version' : version } , 
    { 'projectVersion.localConfig' : { $elemMatch : { version : version } } }).exec(function(err,projectConfig){
        console.log("Result : "+JSON.stringify(projectConfig));        
}); 

我丢失了一些东西,或者有其他方法可以从混合类型中查找子文档。

0 个答案:

没有答案