Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 插入新文档时是否可以仅返回特定字段?_Node.js_Mongodb_Node Mongodb Native - Fatal编程技术网

Node.js 插入新文档时是否可以仅返回特定字段?

Node.js 插入新文档时是否可以仅返回特定字段?,node.js,mongodb,node-mongodb-native,Node.js,Mongodb,Node Mongodb Native,我需要仅使用_id字段获取新文档。大概是这样的: db.users.insert({name: 'Jonh', age: 27}, {_id: true} , function (err, user) { if (err) {} // need to be user with only _id field. }); 我如何才能做到这一点?已更新 insert回调函数的第二个参数始终是插入对象的数组,并且不能阻止其他字段被包括在内。但是,您可以使用创建要查找的结果: db.user

我需要仅使用_id字段获取新文档。大概是这样的:

db.users.insert({name: 'Jonh', age: 27}, {_id: true} , function (err, user) {
   if (err) {}

   // need to be user with only _id field.
});

我如何才能做到这一点?

已更新

insert
回调函数的第二个参数始终是插入对象的数组,并且不能阻止其他字段被包括在内。但是,您可以使用创建要查找的结果:

db.users.insert({name: 'Jonh', age: 27}, {_id: true} , function (err, users) {
    if (err) {}

    users = users.map(function(user) {
        return {_id: user._id};
    });

    // users now contains objects with just the _id field   
});

如果我将使用批插入怎么办?我应该使用loop吗?@Erik查看更新答案,因为您可以使用
Array#map
获得更干净的解决方案。