首页 > 解决方案 > 如何使用以美元符号开头的字符串值更新 mongodb 中的字段

问题描述

我正在尝试将散列密码保存到 mongodb,但问题似乎是 bcrypt 给出的结果字符串以美元符号开头。不是更新该字段,而是删除该字段。

以下是相关代码:

const hash = await bcrypt.hash(password, 10);

collection.updateOne({ email }, [
  { $set: { hash } }
]);

标签: node.jsmongodb

解决方案


那么应该是这个

{ $set: { hash: hash } }

或者让它更清楚一点:

const hash_value = await bcrypt.hash(password, 10);
collection.updateOne({ email }, [
  { $set: { "hash": hash_value } }
]);

我想{ email }有同样的问题,一定很可能你正在寻找{ email: email }

看这个例子:

var hash1 = "bar"
var hash2 = "$bar"

db.collection.insertMany([{ _id: 1, hash1: "foo" }, { _id: 2, hash2: "foo" }])

db.collection.updateOne({ _id: 1 }, [{ $set: { hash1 } }]);
db.collection.updateOne({ _id: 2 }, [{ $set: { hash2 } }]);

db.collection.find()


{ "_id" : 1.0, "hash1" : "bar" },
{ "_id" : 2.0 }

在 Mongo 4.4 及更早版本$中不允许使用,请参阅字段名称

顶级字段名称不能以美元符号 ($) 字符开头。

MongodB 5.0 添加了对在字段名称中使用 ( $) 和 ( )的改进支持。.有一些限制。有关详细信息,请参阅字段名称注意事项。

一般来说,我不建议在字段名称中使用 ( $) 和 ( )。.无论如何,动态字段名称很糟糕。


推荐阅读