Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
MongoDB查询,如果值不为null,则更新特定字段_Mongodb_Mongodb Query - Fatal编程技术网

MongoDB查询,如果值不为null,则更新特定字段

MongoDB查询,如果值不为null,则更新特定字段,mongodb,mongodb-query,Mongodb,Mongodb Query,我有一个对象“输入”,将像参数一样传递给查询: var input = { id: 1, componentId: x, commands: [...], user: [...], } 以及集合“testCollection”: testCollection = { id: 1, model: { stepComponents: [ { componentId: x

我有一个对象“输入”,将像参数一样传递给查询:

var input = {
    id: 1,
    componentId: x,
    commands: [...],
    user: [...],
}
以及集合“testCollection”:

testCollection = {
    id: 1,
    model: {
        stepComponents: [
           {  
            componentId: x
            command: [...],
            user: [...],
           }
         ]
    }
}
我的问题是如何更新“testCollection”上的特定字段,并在其未定义或为空时跳过更新。 这意味着如果“input.user”未定义/null,则不更新“user”字段

更新查询示例如下所示:

testCollection.update(
  {
    _id: objectId(input.id),
    'model.stepComponents.componentId': input.componentId
  },
  {
    'inputs': input.inputs,
    'model.stepComponents.$.commands': input.commands,
    'model.stepComponents.$.users': input.users,
  },
  { upsert: true },
);
任何帮助都将不胜感激。谢谢。

试试这个:

testCollection.update(
{
  _id: objectId(input.id),
  user: {$ne: null}
},
{
    $set: {input}
}
))

试试这个:

testCollection.update(
{
  _id: objectId(input.id),
  user: {$ne: null}
},
{
    $set: {input}
}
))

您可以尝试使用

你可以尝试使用


我被同样的问题所震惊,并通过下面的解决方案得以解决

  let params= {
      id: req.body.id, componentId: req.body.x, commands: req.body...,
  }

  ;
  for(let prop in params) if(!params[prop]) delete params[prop];//it will remove fields who are undefined or null 

  testCollection.findOneAndUpdate( {
      _id: req.params.id
  }

  , params);

我被同样的问题所震惊,并通过下面的解决方案得以解决

  let params= {
      id: req.body.id, componentId: req.body.x, commands: req.body...,
  }

  ;
  for(let prop in params) if(!params[prop]) delete params[prop];//it will remove fields who are undefined or null 

  testCollection.findOneAndUpdate( {
      _id: req.params.id
  }

  , params);

它不适合我的情况,谢谢你的帮助:)它不适合我的情况,谢谢你的帮助:)很抱歉我回复晚了,它解决了我的问题,谢谢。很抱歉我回复晚了,它解决了我的问题,谢谢。