node.js - 使用 Mongoose 查询指定嵌套对象的所有值
问题描述
我目前正在尝试使用 Mongoose 查询 MongoDB 集合,但在尝试将此查询转换为可用的 Mongoose 查询时遇到了麻烦。
MongoDB CLI 查询是db.events.find({}, {'first.points': 1, '_id': 0})
.
这工作正常,并返回我在命令行中运行它时所期望的结果,我尝试了几种将其转换为 Mongoose 查询的方法,到目前为止我的尝试是:
尝试#1
Events.find({}).populate('first').exec(function(err, events){
if(err) { console.log(err) }
console.log(events);
});
这不起作用并Cast to ObjectId failed for value "10" at path "_id" for model "Event"
在启动节点服务器时引发错误。
尝试#2
Event.find({'first.points': "10"}).populate('first').exec(function(err, events)
这不会引发任何错误,并且确实返回了我期望的值,但是我试图返回所有first.points
事件的所有值,但我似乎无法做到这一点。
尝试#3
Event.find({'first.points': "$all"}).populate('first').exec(function(err, events)
这也不起作用,并且是我最近在这个问题上的尝试,这次它再次抛出一个错误说Cast to number failed for value "$all" at path "first.points" for model "Event"
我不确定要为此尝试什么,我不确定如何返回所有值而不指定要查找的值。
编辑
事件的模型包括在下面
var eventsSchema = new mongoose.Schema({
name: String, // The event name, with data type String
date: Date, // Date with data type Date
first: {
points: Number, // The points awarded to the first place with data type Number
house: String
},
second: {
points: Number,
house: String
},
third: {
points: Number,
house: String
},
fourth: {
points: Number,
house: String
}
});
任何帮助表示赞赏。
解决方案
归功于naga - elixir - jar这个答案。
Event.find({}, {'first.points': 1, '_id': 0}, function(err, events) {...})
此代码以正确的格式返回我需要的值,没有错误。
请注意,为了清楚起见,我已将其从箭头函数转换为。箭头功能在这里Event.find({}, {'first.points': 1, '_id': 0}, (err, events) => {...})
推荐阅读
- vue.js - 从 vue-uploader 获取成功上传的文件列表
- sql - SQL:“已超出堆叠诊断区域的最大数量。”
- kubernetes - 新子图表上的 Helm 升级失败
- spring - Spring aop:建议从未达成
- ruby - 尝试学习将 PageObjects 与 Ruby 一起使用 - 出现错误“未初始化的常量站点 (NameError)”
- google-cloud-storage - 使用 wget 等命令行实用程序从谷歌云存储下载公共数据目录
- azure-devops - 没有 Azure DevOps Pipelines - 构建 - 任务
- apache - apache poi:打开包含 AlternateContent 元素的合并 Word 文档时出错
- babeljs - 如何在包裹中使用服务人员?
- ios - Xcode 单元测试失败立即运行(没有)