Mongoose, Select a Specific Field with Find

Mongoose, Select a specific field with find

The _id field is always present unless you explicitly exclude it. Do so using the - syntax:

exports.someValue = function(req, res, next) {
//query with mongoose
var query = dbSchemas.SomeValue.find({}).select('name -_id');

query.exec(function (err, someValue) {
if (err) return next(err);
res.send(someValue);
});
};

Or explicitly via an object:

exports.someValue = function(req, res, next) {
//query with mongoose
var query = dbSchemas.SomeValue.find({}).select({ "name": 1, "_id": 0});

query.exec(function (err, someValue) {
if (err) return next(err);
res.send(someValue);
});
};

mongoose - select specific fields in Model.create

If you take a look at the mongoose-source code, you can see that Model.create returns a promise with the created/inserted documents. There's no way to specify a filtering-options to return only specific fields.

Of course you could do a .find() in combination with a .select() call after creating/inserting a new record but that would result in one extra DB-query for each insert which does not make a lot of sense.

You could instead just return the desired properties from the returned document, since you know that a new document was inserted successfully with the provided data, when the promise resolved. So you could simply do:

res.send({title: generatedEvent.title, description: generatedEvent.description});

Returning specific fields with mongoose

You can specify the fields to return like this:

Order.findOne({'_id' : id})
.select('client.phone client.email orderdetails.status reference')
.exec(function(err, order) {
//
});

Alternative syntax

Order.findOne({'_id' : id})
.select('client.phone client.email orderdetails.status reference')
.exec(function(err, order) {
//
});

I've made a number of assumptions here, but you should be able to see the idea.

Mongoose use of .select() method

the docs say you can achieve this like so:

Mongoose v4.0

// Retrieving only certain fields

Model.find({}, 'first last', function (err, docs) {

});

old outdated API

// Retrieving only certain fields

Model.find({}, ['first', 'last'], function (err, docs) {
// docs is an array of partially-`init`d documents
// defaults are still applied and will be "populated"
});

so you can do this without select().

Unable to select specific field for MongoDB find operation

The standard Node.js MongoDB driver requires a top-level projection property for the options parameter if you wish to project your documents. This would result in the second parameter of your find() call looking like this:

{ projection: { customer_key: 1, _id: 0 } }

This is indicated in the Node.js MongoDB driver API documentation, which is notably not a 1-to-1 match with the MongoDB shell API.

As of the time of this answer, you could find the collection.find() reference here. This reference shows the following method signature (again as of when this answer was written):

find(filter: Filter<WithId<TSchema>>, options?: FindOptions<Document>)

Following the FindOptions parameter takes us to this reference page, which details the various top-level options properties available for the find() method. Among these is the projection property in question.

In short, don't use the normal MongoDB documentation as a reference for your programming language's MongoDB driver API. There will often be disconnects between the two.

Mongoose, find, return specific properties

You use projection. The first example in the mongoose query docs has a projection operation tucked in.

NB: not real code b/c I highlighted the important bits with triple stars

// find each person with a last name matching 'Ghost', ***selecting the `name` and `occupation` fields***
Person.findOne({ 'name.last': 'Ghost' }, ***'name occupation'***, function (err, person) {
if (err) return handleError(err);
console.log('%s %s is a %s.', person.name.first, person.name.last, person.occupation) // Space Ghost is a talk show host.
})

The Person schema isn't specified but I think the example is clear enough.

mongoose: find all the documents that have specific field

You can use $exists in this way:

db.collection.find({
"game": {
"$exists": true
}
})

Example here

Also, another options is compare to not equal null:

db.collection.find({
"game": {
"$ne": null
}
})

Example here



Related Topics



Leave a reply



Submit