mongoose检索只插入推送

时间:2021-08-28 02:34:50

How can I retrieve only the inserted object in the clients array, I insert and then in callback I have all clients and I wanna only the inserted.

我怎样才能检索客户端数组中的插入对象,我插入然后在回调中我有所有客户端,我只想插入。

 User.findOneAndUpdate(
        {_id: req.body.id },
        { $push: { clients: { 

            name: req.body.name,
            tel: req.body.tel,
            itens: req.body.itens

        } } }, {safe: true},

        function(err, model) {

            if(err){

            console.log(err);

            }
            if(!model){

            console.log('Not Found')

            }
            var itens= model.itens;
            //print all clients i wanna to print only the inserted
            console.log(itens);
        }

    );

1 个解决方案

#1


2  

The way I handle it rather than using findOneAndUpdate. I use findOne and then add my object and then push to the array and then save.

我处理它的方式而不是使用findOneAndUpdate。我使用findOne,然后添加我的对象,然后推送到数组,然后保存。

User.findOne({_id: req.body.id }, function(err, model) {
        if(err){
            console.log(err);
        }
        if(!model){
            console.log('Not Found');
        }

        var itemToPush = { 
            _id: mongoose.Types.ObjectId(),
            name: req.body.name,
            tel: req.body.tel,
            itens: req.body.itens
        }; 

        model.clients.push(itemtToPush);
        model.save(function(err,model){
            console.log(itemToPush._id);
            console.log(itemToPush);
        });

    }

);

I am not sure if you are looking for any id or not but that should give you the object you wish to push. Again, might not be the solution you are looking for.

我不确定你是否正在寻找任何id,但是应该给你想要推送的对象。同样,可能不是您正在寻找的解决方案。

#1


2  

The way I handle it rather than using findOneAndUpdate. I use findOne and then add my object and then push to the array and then save.

我处理它的方式而不是使用findOneAndUpdate。我使用findOne,然后添加我的对象,然后推送到数组,然后保存。

User.findOne({_id: req.body.id }, function(err, model) {
        if(err){
            console.log(err);
        }
        if(!model){
            console.log('Not Found');
        }

        var itemToPush = { 
            _id: mongoose.Types.ObjectId(),
            name: req.body.name,
            tel: req.body.tel,
            itens: req.body.itens
        }; 

        model.clients.push(itemtToPush);
        model.save(function(err,model){
            console.log(itemToPush._id);
            console.log(itemToPush);
        });

    }

);

I am not sure if you are looking for any id or not but that should give you the object you wish to push. Again, might not be the solution you are looking for.

我不确定你是否正在寻找任何id,但是应该给你想要推送的对象。同样,可能不是您正在寻找的解决方案。