Using $ in in MongooseJS with nested objects

I successfully used $ in in my node web service when my mongo arrays contained only identifiers. Here is sample data.

{ "_id": { "$oid": "52b1a60ce4b0f819260bc6e5" }, "title": "Sample", "team": [ { "$oid": "52995b263e20c94167000001" }, { "$oid": "529bfa36c81735b802000001" } ], "tasks": [ { "task": { "$oid": "52af197ae4b07526a3ee6017" }, "status": 0 }, { "task": { "$oid": "52af197ae4b07526a3ee6017" }, "status": 1 } ] } 

Please note that tasks are an array, but the identifier is nested in the "task", and in commands it is at the top level. That is where my question is.

In my node route, I usually encounter calling an array of identifiers in my project, this works fine in a command example, but obviously not for my example task.

 app.get('/api/tasks/project/:id', function (req, res) { var the_id = req.params.id; var query = req.params.query; models.Projects.findById(the_id, null, function (data) { models.Tasks.findAllByIds({ ids: data._doc.tasks, query: query }, function(items) { console.log(items); res.send(items); }); }); }); 

This is related to my model, which has the findAllByIds method

 module.exports = function (config, mongoose) { var _TasksSchema = new mongoose.Schema({}); var _Tasks = mongoose.model('tasks', _TasksSchema); /***************** * Public API *****************/ return { Tasks: _Tasks, findAllByIds: function(data, callback){ var query = data.query; _Tasks.find({_id: { $in: data.ids} }, query, function(err, doc){ callback(doc); }); } } } 

In this call, I have $ in: data.ids , which works in a simple array, as an example of the β€œcommand” above. As soon as I enclose my object, as with the "task" sample, this no longer works, and I'm not sure how to specify $ in to look at the data.ids array, but use the value of "task".

I would like not to iterate over the data to create an array with a single identifier, and then re-populate the other values ​​after the data is returned, unless that is the only option.

Update

I thought about setting up my mongo style document, although I would still like to know how to do it differently in case this is not possible in the future.

 "tasks": { "status0": [ { "$oid": "52995b263e20c94167000001" }, { "$oid": "529bfa36c81735b802000001" } ], "status1": [ { "$oid": "52995b263e20c94167000001" }, { "$oid": "529bfa36c81735b802000001" } ] } 
0
source share
2 answers

You can call map in the tasks array to project it into a new array with only ObjectId values:

 models.Tasks.findAllByIds({ ids: data.tasks.map(function(value) { return value.task; }), query: query }, function(items) { ... 
0
source
0
source

All Articles