Document:
{ "_id" : ObjectId("560c24b853b558856ef193a3"), "name" : "Karl Morrison", "pic" : "", "language" : ObjectId("560c24b853b558856ef193a2"), "cell" : 1, "local" : { "email" : "[email protected]", "password" : "12345" }, "sessions" : [ { "id" : ObjectId("560c24b853b558856ef193a5") } ] }
This works:
yield new Promise(function (resolve, reject) { users.col.aggregate([ { $match: { 'name': 'Karl Morrison' } } ], function (err, res) { console.log('err ' + err); console.log('res ' + JSON.stringify(res)); // <-- echos the object retrieved if (err === null) resolve(res); reject(err); }); });
This does not work:
yield new Promise(function (resolve, reject) { users.col.aggregate([ { $match: { '_id': '560c24b853b558856ef193a3' // <-- _id of the user } } ], function (err, res) { console.log('err ' + err); console.log('res ' + JSON.stringify(res)); if (err === null) resolve(res); reject(err); }); });
The .col
access the native mongodb object (using co-monk otherwise). So I'm doing it manually. This however isn't working. I suspect I am not casting the id hexstring to an ObjectId. No matter what I try nothing works.
_id field is reserved for primary key in mongodb, and that should be a unique value. If you don't set anything to _id it will automatically fill it with "MongoDB Id Object". But you can put any unique info into that field.
The $match stage of the pipeline can be used to filter documents so that only ones meeting certain criteria move on to the next stage. In this article, we'll discuss the $match stage in more detail and provide examples that illustrate how to perform match aggregation in MongoDB.
The MongoDB $match operator filters the documents to pass only those documents that match the specified condition(s) to the next pipeline stage.
In MongoDB, aggregation operations process the data records/documents and return computed results. It collects values from various documents and groups them together and then performs different types of operations on that grouped data like sum, average, minimum, maximum, etc to return a computed result.
const ObjectId = mongoose.Types.ObjectId; const User = mongoose.model('User') User.aggregate([ { $match: { _id: ObjectId('560c24b853b558856ef193a3') } } ])
Try this
const User = require('User') const mongoose = require("mongoose"); User.aggregate([ { $match: { _id: new mongoose.Types.ObjectId('560c24b853b558856ef193a3') } } ])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With