首页 > 解决方案 > 使用 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
   }
});

任何帮助表示赞赏。

标签: node.jsmongodbexpressmongoose

解决方案


归功于naga - elixir - jar这个答案。

Event.find({}, {'first.points': 1, '_id': 0}, function(err, events) {...})

此代码以正确的格式返回我需要的值,没有错误。

请注意,为了清楚起见,我已将其从箭头函数转换为。箭头功能在这里Event.find({}, {'first.points': 1, '_id': 0}, (err, events) => {...})


推荐阅读