我正在考虑使用最佳实践来解决 Mongoose 的以下问题。
我有三个模式:
const SchemaA = new Schema({
name: String
});
const SchemaB = new Schema({
schemaA: {
type: Schema.Types.ObjectId,
ref: 'SchemaA',
required: true
}
});
const SchemaC = new Schema({
schemaB: {
type: Schema.Types.ObjectId,
ref: 'SchemaB'
},
user: {
type: Schema.Types.ObjectId,
ref: 'User'
}
});
我需要通过附加了 schemaC 的 schemaA id 获取 schemaB 对象,但由用户过滤。
getSchemaBs: async (schemaAId, userId) => {
try {
SchemaB.find({ schemaA: schemaAId }).populate('schemaC': where user === userId);
} catch (e) {
throw new Error('An error occurred while getting schemasB for specified schemaA.');
};
我正在重构使用 NodeJS 的 Mongo native 驱动程序编写的代码。现在我想使用 Mongoose 使其更简单。
早期版本的代码(请记住它不能遵循最佳实践):
getList: function (schemaAId, userId) {
return new Promise(
function (resolve, reject) {
db.collection('schemaB').aggregate([{
$match: {
'isDeleted': false,
'schemaA': ObjectID(schemaAId)
}
},
{
$lookup: {
from: "schemaC",
localField: "_id",
foreignField: "schemaBId",
as: "schemasC"
},
},
{
$project: {
_id: true,
schemaAId: true,
// other neccessary fields with true (several lines - makes code ugly and messy)
schemasC: {
"$arrayElemAt": [{
$filter: {
input: "$schamasC",
as: "schemaC",
cond: {
$eq: ["$$schemaC.userId", ObjectID(userId)]
}
}
}, 0]
}
}
}
]).toArray(function (error, result) {
if (error) {
reject(error);
} else {
resolve(result);
};
});
});
}
我怎样才能最好地处理这个问题?
最佳答案
使用 mongodb 3.6 可以更好地完成您正在尝试做的事情 $lookup在 $lookup 中过滤文档的语法流水线
db.collection('schemaB').aggregate([
{ "$match": { "isDeleted": false, "schemaA": ObjectID(schemaAId) }},
{ "$lookup": {
"from": "schemaC",
"let": { "schemaBId": "$_id" },
"pipeline": [
{ "$match": {
"$expr": { "$eq": ["$schemaBId", "$$schemaBId"] },
"userId": ObjectID("5b5c747d8209982630bbffe5")
}}
],
"as": "schemasC"
}}
])
关于node.js - 具有 $lookup 聚合的多条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53573605/
我想安装一个带有一些身份验证的私有(private)Rubygem服务器。我希望能够使用公共(public)Ubuntu服务器托管内部gem。我读到了http://docs.rubygems.org/read/chapter/18.但是那个没有身份验证-如我所见。然后我读到了https://github.com/cwninja/geminabox.但是当我使用基本身份验证(他们在他们的Wiki中有)时,它会提示从我的服务器获取源。所以。如何制作带有身份验证的私有(private)Rubygem服务器?这是不可能的吗?谢谢。编辑:Geminabox问题。我尝试“捆绑”以安装新的gem..
我有一个用户工厂。我希望默认情况下确认用户。但是鉴于unconfirmed特征,我不希望它们被确认。虽然我有一个基于实现细节而不是抽象的工作实现,但我想知道如何正确地做到这一点。factory:userdoafter(:create)do|user,evaluator|#unwantedimplementationdetailshereunlessFactoryGirl.factories[:user].defined_traits.map(&:name).include?(:unconfirmed)user.confirm!endendtrait:unconfirmeddoenden
我有一些代码在几个不同的位置之一运行:作为具有调试输出的命令行工具,作为不接受任何输出的更大程序的一部分,以及在Rails环境中。有时我需要根据代码的位置对代码进行细微的更改,我意识到以下样式似乎可行:print"Testingnestedfunctionsdefined\n"CLI=trueifCLIdeftest_printprint"CommandLineVersion\n"endelsedeftest_printprint"ReleaseVersion\n"endendtest_print()这导致:TestingnestedfunctionsdefinedCommandLin
我有一个只接受一个参数的方法:defmy_method(number)end如果使用number调用方法,我该如何引发错误??通常,我如何定义方法参数的条件?比如我想在调用的时候报错:my_method(1) 最佳答案 您可以添加guard在函数的开头,如果参数无效则引发异常。例如:defmy_method(number)failArgumentError,"Inputshouldbegreaterthanorequalto2"ifnumbereputse.messageend#=>Inputshouldbegreaterthano
我正在使用Rails3.1并在一个论坛上工作。我有一个名为Topic的模型,每个模型都有许多Post。当用户创建新主题时,他们也应该创建第一个Post。但是,我不确定如何以相同的形式执行此操作。这是我的代码:classTopic:destroyaccepts_nested_attributes_for:postsvalidates_presence_of:titleendclassPost...但这似乎不起作用。有什么想法吗?谢谢! 最佳答案 @Pablo的回答似乎有你需要的一切。但更具体地说...首先改变你View中的这一行对此#
我从用户Hirolau那里找到了这段代码:defsum_to_n?(a,n)a.combination(2).find{|x,y|x+y==n}enda=[1,2,3,4,5]sum_to_n?(a,9)#=>[4,5]sum_to_n?(a,11)#=>nil我如何知道何时可以将两个参数发送到预定义方法(如find)?我不清楚,因为有时它不起作用。这是重新定义的东西吗? 最佳答案 如果您查看Enumerable#find的文档,您会发现它只接受一个block参数。您可以将它发送两次的原因是因为Ruby可以方便地让您根据它的“并行赋
RSpec似乎按顺序匹配方法接收的消息。我不确定如何使以下代码工作:allow(a).toreceive(:f)expect(a).toreceive(:f).with(2)a.f(1)a.f(2)a.f(3)我问的原因是a.f的一些调用是由我的代码的上层控制的,所以我不能对这些方法调用添加期望。 最佳答案 RSpecspy是测试这种情况的一种方式。要监视一个方法,用allowstub,除了方法名称之外没有任何约束,调用该方法,然后expect确切的方法调用。例如:allow(a).toreceive(:f)a.f(2)a.f(1)
我的Gallery模型中有以下查询:media_items.includes(:photo,:video).rank(:position_in_gallery)我的图库模型有_许多媒体项,每个都有一个照片或视频关联。到目前为止,一切正常。它返回所有media_items包括它们的photo或video关联,由media_item的position_in_gallery属性排序。但是我现在需要将此查询返回的照片限制为仅具有is_processing属性的照片,即nil。是否可以进行相同的查询,但条件是返回的照片等同于:.where(photo:'photo.is_processingIS
除了可访问性标准不鼓励使用这一事实指向当前页面的链接,我应该怎么做重构以下View代码?#navigation%ul.tabbed-ifcurrent_page?(new_profile_path)%li{:class=>"current_page_item"}=link_tot("new_profile"),new_profile_path-else%li=link_tot("new_profile"),new_profile_path-ifcurrent_page?(profiles_path)%li{:class=>"current_page_item"}=link_tot("p
我有一个应用需要发送用户事件邀请。当用户邀请friend(用户)参加事件时,如果尚不存在将用户连接到该事件的新记录,则会创建该记录。我的模型由用户、事件和events_user组成。classEventdefinvite(user_id,*args)user_id.eachdo|u|e=EventsUser.find_or_create_by_event_id_and_user_id(self.id,u)e.save!endendend用法Event.first.invite([1,2,3])我不认为以上是完成我的任务的最有效方法。我设想了一种方法,例如Model.find_or_cr