本文介绍了通过变量获取位置,然后在mongodb中修改特定对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使该查询使用我的变量而不是硬编码0?

How can I make this query use my variable instead of the hard coded 0?

let pos = 0;

{$set: {'answers.0.acknowledged': data}}

推荐答案

通常,您的选择是模板文字 Array.join String.concat 等:

Usually you choices are template literals, Array.join, String.concat etc:

let pos = 0;
let data = 'data';

let query = {$set: {[['answers.', pos,'.acknowledged'].join('')]: data}}

console.log(query);

使用 String.concat :

let pos = 0;
let data = 'data';
let query = {$set: {['answers.'.concat(pos,'.acknowledged')]: data}}
console.log(query);

Array.join String.concat 具有更好的浏览器支持,其中模板文字可以不是.如果要在客户端使用它们.如果您在后端使用它们,则可能不必担心.

Array.join, String.concat has a much better browsers support where template literals do not. If they were to be used @ the client side. In your case if you are using them at the back end you probably have nothing to worry about.

这篇关于通过变量获取位置,然后在mongodb中修改特定对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 19:13