kamesh
kamesh

Reputation: 421

Projection in findAndModify query in nodejs mongodb driver

I was unable to project only required fields from findAndModify query, it is returning whole document.

var MongoClient = require('mongodb').MongoClient;


db.collection("conf").findAndModify(
    searchDoc,
    sortDoc,
    {$set: updateDoc},
    {new: true},
    {"required_field": 1},
    function (error, obj) {
        console.log(obj["value"]);
        db.close();
    });

Upvotes: 3

Views: 971

Answers (2)

t_yamo
t_yamo

Reputation: 779

refs. https://mongodb.github.io/node-mongodb-native/markdown-docs/insert.html#find-and-modify

refs. https://github.com/mongodb/node-mongodb-native/blob/V2.1.3/lib/collection.js#L2319

collection.findAndModify(criteria[, sort[, update[, options]]], callback)

optons is key-value pair. it need field name. try following.

var MongoClient = require('mongodb').MongoClient;

db.collection("conf").findAndModify(
    searchDoc,          // criteria
    sortDoc,            // sort
    {$set: updateDoc},  // update
    {                   // options
        new: true,
        fields: {"required_field": 1}
    },
    function (error, obj) {
        console.log(obj["value"]);
        db.close();
    });

Upvotes: 4

somallg
somallg

Reputation: 2033

Seems like you are using function findAndModify of mongodb nodejs driver. That options object is not for projection but for the behavior of the function

Options object can be used for the following options:

remove - if set to true (default is false), removes the record from the collection. Callback function still gets the object but it doesn’t exist in the collection any more.

new - if set to true, callback function returns the modified record. Default is false (original record is returned)

upsert - if set to true and no record matched to the query, replacement object is inserted as a new record

Even through the function findAndModify share the same name with a function of mongo shell, it may behave differently.You should check the doc here (https://mongodb.github.io/node-mongodb-native/markdown-docs/insert.html#find-and-modify)

Upvotes: 0

Related Questions