te')); return $arr; } /* 遍历用户所有主题 * @param $uid 用户ID * @param int $page 页数 * @param int $pagesize 每页记录条数 * @param bool $desc 排序方式 TRUE降序 FALSE升序 * @param string $key 返回的数组用那一列的值作为 key * @param array $col 查询哪些列 */ function thread_tid_find_by_uid($uid, $page = 1, $pagesize = 1000, $desc = TRUE, $key = 'tid', $col = array()) { if (empty($uid)) return array(); $orderby = TRUE == $desc ? -1 : 1; $arr = thread_tid__find($cond = array('uid' => $uid), array('tid' => $orderby), $page, $pagesize, $key, $col); return $arr; } // 遍历栏目下tid 支持数组 $fid = array(1,2,3) function thread_tid_find_by_fid($fid, $page = 1, $pagesize = 1000, $desc = TRUE) { if (empty($fid)) return array(); $orderby = TRUE == $desc ? -1 : 1; $arr = thread_tid__find($cond = array('fid' => $fid), array('tid' => $orderby), $page, $pagesize, 'tid', array('tid', 'verify_date')); return $arr; } function thread_tid_delete($tid) { if (empty($tid)) return FALSE; $r = thread_tid__delete(array('tid' => $tid)); return $r; } function thread_tid_count() { $n = thread_tid__count(); return $n; } // 统计用户主题数 大数量下严谨使用非主键统计 function thread_uid_count($uid) { $n = thread_tid__count(array('uid' => $uid)); return $n; } // 统计栏目主题数 大数量下严谨使用非主键统计 function thread_fid_count($fid) { $n = thread_tid__count(array('fid' => $fid)); return $n; } ?>javascript - MongoDBMongoose: Updating entire document with findOneAndUpdate() - Stack Overflow
最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - MongoDBMongoose: Updating entire document with findOneAndUpdate() - Stack Overflow

programmeradmin4浏览0评论

I want to use the findOneAndUpdate() method to either create a document if it doesn't exist, or update it if does exist. Consider the following code:

SampleComment = new Comment({
    id: '00000001',
    name: 'My Sample Comment',
    ...
})

This is my attempt to find out if SampleComment aldready exists, and if so, update it, otherwise creating it:

Comment.findOneAndUpdate(
    { id: SampleComment.id }, 
    { SampleComment }, // <- NOT PASSING THE OBJECT
    { upsert: true, setDefaultsOnInsert: true }, 
    function(error, result) {
        ...
});

I'm trying to pass the Model-instance as an object in the second argument, but result is only returning the default values of the model. Same goes for the document itself.

How do I pass the entire object SampleComment correctly in the second argument?

I want to use the findOneAndUpdate() method to either create a document if it doesn't exist, or update it if does exist. Consider the following code:

SampleComment = new Comment({
    id: '00000001',
    name: 'My Sample Comment',
    ...
})

This is my attempt to find out if SampleComment aldready exists, and if so, update it, otherwise creating it:

Comment.findOneAndUpdate(
    { id: SampleComment.id }, 
    { SampleComment }, // <- NOT PASSING THE OBJECT
    { upsert: true, setDefaultsOnInsert: true }, 
    function(error, result) {
        ...
});

I'm trying to pass the Model-instance as an object in the second argument, but result is only returning the default values of the model. Same goes for the document itself.

How do I pass the entire object SampleComment correctly in the second argument?

Share Improve this question edited Aug 2, 2021 at 13:39 J.F. 15.2k9 gold badges38 silver badges72 bronze badges asked Jun 14, 2016 at 23:27 Comfort EagleComfort Eagle 2,4625 gold badges25 silver badges51 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 7

What's actually happening when you're calling findOneAndUpdate() with your Document object as your update object with { SampleComment } is you're destructuring that to be SampleComment : {...}.

Mongoose will then go and look at your database document for any property named SampleComment, find none, and then do nothing. Returning to you a document where nothing would have changed.

What you can do to fix this is convert your Document back to a plain update object first with Mongoose's toObject() method, remove the _id (since that property is immutable and you don't want to replace it anyway with an update) and then save it with your existing findOneAndUpdate() method. eg:

let newComment = SampleComment.toObject();
delete newComment._id;

Comment.findOneAndUpdate(
    { id: SampleComment.id }, 
    newComment,
    { upsert: true, setDefaultsOnInsert: true }, 
    function(error, result) {
        ...
    }
);

You can then see the updated document in your database. To receive the updated document in your result you need to also pass the option { new: true } to your options object.

Here's the link to Mongoose's toObject() Document method documentation.

By default the returned result is going to be the unaltered document. If you want the new, updated document to be returned you have to pass an additional argument named new with the value true.

Comment.findOneAndUpdate({id: SampleComment.id}, SampleComment, {new: true, upsert: true, setDefaultsOnInsert: true}, function(error, result) {
    if(error){
        console.log("Something wrong when updating data!");
    }

    console.log(result);
});

See http://mongoosejs./docs/api.html#query_Query-findOneAndUpdate:

function(error, doc) {
  // error: any errors that occurred
  // doc: the document before updates are applied if `new: false`, or after updates if `new = true`
}

I found the way to make it easy and fast :D

In my case I Just needed to insert the object from a form and update the doc. Maybe that helps someone:

Angularjs Controller:

  $scope.bike ={};
  fBikeFactory.get({
        id:$stateParams.id
      })
      .$promise.then(function (response) {
        $scope.bike = response;
      },function (response) {
        $scope.bike = "Error: " + response.status + " " + response.statusText;
      });


// UPDATE a BIKE
      $scope.saveBike = function() {
        $scope.processing = true;

        var updateQuery = fBikeFactory.update({id: $stateParams.id}, $scope.bike);
        updateQuery.$promise.then(function(rep) {
            $scope.processing = false;
            $scope.message = "Desat amb èxit";
            setTimeout(function(){ $state.go('home.adminBikes');$scope.bike.message = ''; }, 750);
        },function(err) {
            $scope.processing = false;
            $scope.message = 'Error al Desar, torna a provar-ho.';
        })
      };

Require the model:

var Bike = require('../models/bikeModel.js');

...

ROUTE:

bikesRouter.route('/bikes/:id')
    .put(function(req,res) {


    Bike.findOneAndUpdate(
            {_id: req.params.id}, // find a document with that filter
            req.body, // document to insert 
            {upsert: true, new: true, runValidators: true}, // options
            function (err, updatedBike) { // callback
                if (err) console.log('ERROR '+ err);
                else res.json(updatedBike)

            }
        );
    });

Hope that helps :D

发布评论

评论列表(0)

  1. 暂无评论