node.js - Mongo查找转换为不同的对象

标签 node.js mongodb

我对 Mongo 有点陌生,并且已经尝试过 Mongoose for Node.js

我的问题具体是关于“查找”结果的形成方式。 假设架构如下所示,具有三个属性。

 var schema = {
    attr1: {
        type: String,
        required: true
    },
    attr2: {
        type: String,
        required: true
    },
    attr3: {
        type: Number,
        required: true
    }

我们将搜索“attr1”为“value1”的所有条目,如下所示

dataModel.find({'attr1':'value1'}, {attr2:1, attr3:1, _id:0}, resultsFunction)

'resultsFunction' 将以所有对象数组的形式接收结果文档。假设我们得到两个结果,看起来像这样

[  { attr2: value1 ,
     attr3: value2 }, 
   { attr2: value3,
     attr3: value4 }]

这就是我正在努力解决的问题。我不希望生成的对象具有与架构相同的属性名称。相反,我希望将其转换为自定义对象

[  { customAttr2: value1 ,
     customAttr3: value2 }, 
   { customAttr2: value3,
     customAttr3: value4 }]

有没有办法从 Mongodb 的 API 中搜索和形成此类对象? (而不是编写可能影响性能的我自己的转换/函数)

最佳答案

dataModel.aggregate([{$match:{'attr1':'value1'}}, {$project:{customAttr2:"$attr2", customAttr3:"$attr3", _id:0}}], resultsFunction)

关于node.js - Mongo查找转换为不同的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48703952/

相关文章:

css - 使用 express 中间件应用 CSS 样式

Node.js - 检查用户是否存在

node.js - 有没有办法在动态嵌入对象上使用聚合或 $sum ?

node.js - 将用户凭据从前端传递到 Node 后端的最安全方法是什么

javascript - NodeJS Express 要求和启动

javascript - 使用 mongodb 收集 meteor 时出现重复的键

javascript - 如何理解session和flash?

javascript - 如何转换 mongo ObjectId .toString 而不包含 'ObjectId()' 包装器——仅包含值?

node.js - 如何将 Azure Httptrigger 连接到网站?

javascript - ./~/node-env-file/lib/index.js 中的错误找不到模块 : Error: Cannot resolve module 'fs'