有没有办法使用node-mongodb-native的动态密钥? [英] Is there any way to use a dynamic key with node-mongodb-native?

查看:87
本文介绍了有没有办法使用node-mongodb-native的动态密钥?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在node-mongodb-native驱动程序中使用动态密钥?我的意思是让变量持有密钥而不是直接使用密钥。

Is there any way to use dynamic keys with the node-mongodb-native driver? By this I mean having a variable hold the key instead of using the key directly.

正如通常那样:

db.createCollection('col', function(err, col){
    col.insert({'_id':'wak3ajakar00'});
}

代替这样做:

db.createCollection('col', function(err, col){
    var ID = '_id';
    col.insert({ID:'wak3ajakar00'});
}

当我运行后一个代码时,我最终得到了除了标准创建的 _id 之外,集合db.col中的文档带有一个名为 ID 的键,而不是仅仅一个键 _id ,其值为 wak3ajakar00 。这让我相信实际上不可能直接这样做。

When I run the latter code, I end up with a document in collection db.col with a key called ID in addition to a standardly created _id, as opposed to just a key _id with the value wak3ajakar00. This leads me to believe that it isn't actually possible to do this directly.

相反,我现在只是创建我想提前插入的文档,如下所示:

Instead, I'm now just creating the document that I want to insert ahead of time as follows:

db.createCollection('col', function(err, col){
    var ID = 'wak3ajakar00';
    var key = '_id';
    insertion = {}
    insertion[key] = ID;
    col.insert(insertion);
}

这与我想要的完全一样,但我只是想知道是否有更好的方法可以解决这个问题。 JavaScript,NodeJS和MongoDB对我来说都是新手,所以我觉得我很容易丢失一些东西。如果没有,有没有更简洁的方法在JavaScript中编写上述代码?

This works exactly like I want it to, but I just wanted to know if there are any better ways to go about this. JavaScript, NodeJS, and MongoDB are all new to me, so I feel like I could easily be missing something. If not, are there any cleaner ways to write the above code in JavaScript?

最好,谢谢,
萨米

Best, and thanks,
Sami

推荐答案

在对象文字语法中,不能将变量用作键名,只能使用值。这样做的方法是你已经发现的方式 - 首先创建你的对象,然后使用方括号表示法将属性作为一个单独的步骤添加。

In object literal syntax, you cannot use a variable as the key name, only values. The way to do it, is the way you already discovered - create your object first, then add the property as a separate step using square bracket notation.

var obj = {};
var ID = "_id";
obj[ID] = "wak3ajakar00";

这篇关于有没有办法使用node-mongodb-native的动态密钥?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆