我遇到了一个基本请求的问题。 我获取的 Mongoose 模型的所有属性在 exec() 回调中均未定义。
这是我的架构:
userSchema: new Schema({
email: { type: String, limit: 50, index: true },
password: String,
birthdate: { type: Date },
active: { type: Boolean, default: true },
friends: [{
_friend: { type: Schema.ObjectId, ref: 'User' },
addedDate: { type: Date, default: Date.now }
}],
registrationDate: { type: Date, default: Date.now }
})
您可能已经注意到我的“ friend ”属性是引用另一个模式的对象数组。
现在这是我的查询:
dbModels.User
.find({ _id: req.session.user._id })
.populate('friends._friend', 'email birthdate')
.exec(function (err, _user){
if (err || !_user){
apiUtils.errorResponse(res, sw, 'Error when fetching friends.', 500);
} else {
console.log('user', _user);
// This output the object with all its properties
console.log('user birthdate', _user.birthdate);
// _user.birthdate is undefined
console.log('user friends', _user.friends);
// _user.friends is undefined
apiUtils.jsonResponse(res, sw, _user);
}
});
当此 Web 服务返回“_user”时,每个属性都已明确定义并具有正确的值。 问题是我只想返回 _user.friends,这是不可能的,因为它是未定义的。
现在,这里是 apiUtils.jsonResponse 函数:
exports.jsonResponse = function (res, sw, body) {
console.log(body.friends);
// At this breakpoint, body.friends is still undefined
(sw || _sw).setHeaders(res);
if (util.isArray(body)) {
for (var i = 0; i < body.length; i++) {
body[i] = exports.cleanResults(body[i]);
}
} else {
console.log(body.friends);
// At this breakpoint body.friends is still undefined
body = exports.cleanResults(body);
}
res.send(httpCode || 200, JSON.stringify(body));
};
还有 cleanResults 函数:
exports.cleanResults = function (body) {
console.log(body.friends);
// At this point, body.friends is FINALLY DEFINED
if (typeof body.toObject === 'function') {
body = body.toObject();
delete body.__v;
}
for (var attr in body) {
if (body.hasOwnProperty(attr) && attr[0] == '_') {
var _attr = attr.replace('_', '');
body[_attr] = body[attr];
delete body[attr];
}
}
return body;
};
我尝试设置超时以查看问题是否来自异步,但它没有任何改变。我此时有点绝望,我想知道你以前是否遇到过同样的问题?
最佳答案
我明白了你的问题,你不小心使用了 find 当你希望只返回一个对象时。在这种情况下,您应该使用 findById:
User
.findById(req.session.user._id)
.populate('friends._friend', 'name surname picture birthdate')
.exec(function(err, user) {
...
})
关于node.js - Mongoose 模型在填充后获得未定义的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25838007/
我正在尝试设置一个puppet节点,但rubygems似乎不正常。如果我通过它自己的二进制文件(/usr/lib/ruby/gems/1.8/gems/facter-1.5.8/bin/facter)在cli上运行facter,它工作正常,但如果我通过由rubygems(/usr/bin/facter)安装的二进制文件,它抛出:/usr/lib/ruby/1.8/facter/uptime.rb:11:undefinedmethod`get_uptime'forFacter::Util::Uptime:Module(NoMethodError)from/usr/lib/ruby
我有一个模型:classItem项目有一个属性“商店”基于存储的值,我希望Item对象对特定方法具有不同的行为。Rails中是否有针对此的通用设计模式?如果方法中没有大的if-else语句,这是如何干净利落地完成的? 最佳答案 通常通过Single-TableInheritance. 关于ruby-on-rails-Rails-子类化模型的设计模式是什么?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.co
我正在使用的第三方API的文档状态:"[O]urAPIonlyacceptspaddedBase64encodedstrings."什么是“填充的Base64编码字符串”以及如何在Ruby中生成它们。下面的代码是我第一次尝试创建转换为Base64的JSON格式数据。xa=Base64.encode64(a.to_json) 最佳答案 他们说的padding其实就是Base64本身的一部分。它是末尾的“=”和“==”。Base64将3个字节的数据包编码为4个编码字符。所以如果你的输入数据有长度n和n%3=1=>"=="末尾用于填充n%
我需要从一个View访问多个模型。以前,我的links_controller仅用于提供以不同方式排序的链接资源。现在我想包括一个部分(我假设)显示按分数排序的顶级用户(@users=User.all.sort_by(&:score))我知道我可以将此代码插入每个链接操作并从View访问它,但这似乎不是“ruby方式”,我将需要在不久的将来访问更多模型。这可能会变得很脏,是否有针对这种情况的任何技术?注意事项:我认为我的应用程序正朝着单一格式和动态页面内容的方向发展,本质上是一个典型的网络应用程序。我知道before_filter但考虑到我希望应用程序进入的方向,这似乎很麻烦。最终从任何
我希望我的UserPrice模型的属性在它们为空或不验证数值时默认为0。这些属性是tax_rate、shipping_cost和price。classCreateUserPrices8,:scale=>2t.decimal:tax_rate,:precision=>8,:scale=>2t.decimal:shipping_cost,:precision=>8,:scale=>2endendend起初,我将所有3列的:default=>0放在表格中,但我不想要这样,因为它已经填充了字段,我想使用占位符。这是我的UserPrice模型:classUserPrice回答before_val
我在我的项目中添加了一个系统来重置用户密码并通过电子邮件将密码发送给他,以防他忘记密码。昨天它运行良好(当我实现它时)。当我今天尝试启动服务器时,出现以下错误。=>BootingWEBrick=>Rails3.2.1applicationstartingindevelopmentonhttp://0.0.0.0:3000=>Callwith-dtodetach=>Ctrl-CtoshutdownserverExiting/Users/vinayshenoy/.rvm/gems/ruby-1.9.3-p0/gems/actionmailer-3.2.1/lib/action_mailer
我有一个包含模块的模型。我想在模块中覆盖模型的访问器方法。例如:classBlah这显然行不通。有什么想法可以实现吗? 最佳答案 您的代码看起来是正确的。我们正在毫无困难地使用这个确切的模式。如果我没记错的话,Rails使用#method_missing作为属性setter,因此您的模块将优先,阻止ActiveRecord的setter。如果您正在使用ActiveSupport::Concern(参见thisblogpost),那么您的实例方法需要进入一个特殊的模块:classBlah
我有一个表单,其中有很多字段取自数组(而不是模型或对象)。我如何验证这些字段的存在?solve_problem_pathdo|f|%>... 最佳答案 创建一个简单的类来包装请求参数并使用ActiveModel::Validations。#definedsomewhere,atthesimplest:require'ostruct'classSolvetrue#youcouldevencheckthesolutionwithavalidatorvalidatedoerrors.add(:base,"WRONG!!!")unlesss
我想向我的Controller传递一个参数,它是一个简单的复选框,但我不知道如何在模型的form_for中引入它,这是我的观点:{:id=>'go_finance'}do|f|%>Transferirde:para:Entrada:"input",:placeholder=>"Quantofoiganho?"%>Saída:"output",:placeholder=>"Quantofoigasto?"%>Nota:我想做一个额外的复选框,但我该怎么做,模型中没有一个对象,而是一个要检查的对象,以便在Controller中创建一个ifelse,如果没有检查,请帮助我,非常感谢,谢谢
我已经从我的命令行中获得了一切,所以我可以运行rubymyfile并且它可以正常工作。但是当我尝试从sublime中运行它时,我得到了undefinedmethod`require_relative'formain:Object有人知道我的sublime设置中缺少什么吗?我正在使用OSX并安装了rvm。 最佳答案 或者,您可以只使用“require”,它应该可以正常工作。我认为“require_relative”仅适用于ruby1.9+ 关于ruby-主要:Objectwhenrun