My $push method in Mongoose does not work ok

孤街醉人 提交于 2021-02-11 15:02:26

问题


I have a problem understanding why $push creates only one element in nested array and shows only the id of that element

const mongoose = require('mongoose');

let historySchema = new mongoose.Schema({
    time: {
        type:String
    }
})

//users schema

let userSchema = new mongoose.Schema({
    name:{
        type:String,
        
    },
    dob:{
        type:String,
        
    },
    email:{
        type:String,
        
    },
    noOfpeopleClimbing:{
        type: Number,
        default:0
    },
    details:{
        type:String,
        
    },
    status:{
        type: Boolean,
        default: false
    },
    timeIn:{
        type: Number,
        default: 0
    },
    timeOut:{
      type: Number,
      default: 0
    },
    timeFinal:{
      type: Number,
      default: 0
  },
    timeHistory:[{historySchema}]

})

let User = module.exports = mongoose.model("User", userSchema);

I am talking about timeHistory:[{historySchema}] the rest you can ignore. I am running the next test:

app.post('/users/reset_timeIn/:id', function(req,res){

    Users.findOneAndUpdate({_id:req.params.id},{
        timeIn:0,
        timeOut:0,
        timeFinal:0,
        timeHistory:{
            $push: {time:"some text" }
        },
        status:false,
        noOfpeopleClimbing:0



    },function(err){
        if(err){
            console.log(err);
            return
        }else{
            res.redirect(req.get('referer'));
        }
    })
});

time:"some text"is just for testing. The output of this test, no matter how many times I have pushed an elment is like this:

{
            "noOfpeopleClimbing": 0,
            "status": false,
            "timeIn": 0,
            "timeOut": 0,
            "timeFinal": 0,
            "_id": "5fa3faa68b302530fcb6bba5",
            "name": "Name",
            "dob": "1666-02-02",
            "email": "name@name.com",
            "__v": 0,
            "details": "name",
            "timeHistory": [
                {
                    "_id": "5fa44343aece7d37dc532fd9"
                }
            ]
        },

The "timeHistory" should containt the id and the field time:"some text", right? And if i push another record to have that one as in the second object of that array? right? Please help


回答1:


Looks like you're not using $push correctly. Try passing the correct path to the operator, which in your case is:

Users.findByIdAndUpdate(req.params.id, {
    timeHistory: {
        $push: {
            time: "some text"
        }
    }
})

Here's an example on mongoplayground.



来源:https://stackoverflow.com/questions/64703439/my-push-method-in-mongoose-does-not-work-ok

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!