Alpit Anand
Alpit Anand

Reputation: 1258

To save an array in mongoose?

I have been trying to save arrray data in Mongoose. This is my mongoose schema

    var uploadSchema = mongoose.Schema({
    Fbid: String,
    email: String,
    events: [String],
    uplodedImg: [String],

})

And this is how i am trying to save,but nothing is being populated in robomongo What i am doing wrong here

 var uploadImf = new usersuploadImformation({
    Fbid : fb_id,
    email: email,
    events: place ,
    uploadedImg : randome  

});
usersuploadImformation.findOne({
    Fbid : uploadImf.Fbid
},function(err,check){
    if(!check){
        uploadImf.save(function(err, uploadImf){
            if(err){
               console.log("Error found");
            }
            else{
                console.log("Saved");
            }
        })
    }})

I want to update these fields

    {
    "_id" : ObjectId("5a895f520ea9692308ffcf13"),
    "events" : [],
    "uplodedImg" : [],
    "Fbid" : "1661115317267347",
    "email" : "[email protected]",
    "__v" : 0
}

Tried this other code to update and save:

    usersuploadImformation.findOne({Fbid : fb_id},function(err, check){
    if(!check){
        new usersuploadImformation({
            Fbid : fb_id,
            email: email,
            events: place ,
            uploadedImg : randome  
        }).save(function(err, uploadImf){
            if(err){
               console.log("Error found");
            }
            else{
                console.log("Saved");
            }
        });
    }
    else{
        check.events.push({place})
        check.uploadedImg.push({randome})
        check.save();
    }
})

It should save atleast once, i have not written the case of updating here.

Upvotes: 0

Views: 60

Answers (1)

Pavan Vora
Pavan Vora

Reputation: 1744

Try to change your code something like this,

var query = { 'Fbid': fb_id },
    update = {
        $set: { email: email },
        $push: {
            events: place,
            uploadedImg: randome
        }
    },
    options = { upsert: true };

usersuploadImformation.findOneAndUpdate(query, update, options, function (err, data) {
    if (err) {
        // **   
    }
    // ** your extra code       
});

Here what upsert do is, if the document is not present inside your DB then it will automatically save the document for you.

$set will update the given field and $push will push place to events array and randome to uploadImg array.

Upvotes: 2

Related Questions