在MongoDB中存储动态值,该值指的是其他属性

发布于 2025-02-11 20:44:24 字数 294 浏览 1 评论 0原文

我在节点JS -MongoDB工作。我有一个要求,我需要在MongoDB中存储和检索数据,这些数据是动态的,并指代集合中的其他键。 例子: firstName:字符串 lastname:字符串, fullname:字符串

假设我们插入像下面的记录

{ firstName:“你好”, 姓:“世界”, fullname:“名称lastname” }

现在,当我们检索记录时,将有望显示实际名称。在前端,我们可以使用字符串插值之类的东西以角度实现。有什么办法可以在后端直接处理此表达式。我的实际用例涉及更复杂的结构,因此不可能依靠前端。

I am working in Node js - mongoDB . I have a requirement where I need to store and retrieve data in mongoDB which are dynamic and refers to other keys in the collection.
Example:
firstName : string
lastName : string,
fullName : string

Assume we insert a record like below

{
firstName : "hello",
lastName : "world",
fullName : " firstName lastName"
}

Now when we retrieve the record the fullName field is expected to show the actual name . In front end , we could use something like string interpolation to achieve this in angular. Is there any way I can directly handle this expression in backend . My actual use case involves more complex structures hence it is not possible to rely on front end.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

夜访吸血鬼 2025-02-18 20:44:24

Mongo聚合可以用于执行此操作:

let userProps = await users.aggregate([
  {$match: {_id: ObjectId(_id)}},
  {$unset : ["unusedProps"]},
  {$addFields:{fullName: { $concat: [ "$firstName", " - ", "$lastName" ] }}}
])

这将返回带有全名字段的文档。

Mongo聚集可用于使构建的运算符量=)使更复杂的查询。

Mongo aggregations can be used to do this :

let userProps = await users.aggregate([
  {$match: {_id: ObjectId(_id)}},
  {$unset : ["unusedProps"]},
  {$addFields:{fullName: { $concat: [ "$firstName", " - ", "$lastName" ] }}}
])

This will return a document with a fullName field.

Mongo aggregation can be used to make way more complex queries with the amount of operators builded in =)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文