Anna K
Anna K

Reputation: 1774

create or update mongodb with an object [node.js]

Im trying to create/update mongodb

Why do I get always an error with this code?

My DB schema:

var userSchema = new Schema({
  userAddress: {street: {type: String}, city: {type: String}, zip: {type: String}},
  userId: { type: String, required: true, unique: true },

});

var AddressObj = { street:address['addressLine1'], city:address['city'], zip:address['postalCode']  };


User.findOneAndUpdate(
        {userId:  userID}, 
        { $set: { "userAddress" : AddressObj} },
        function(err, doc){
            if(err){
                console.log("Something wrong when updating data!");
            }

            console.log(doc);
        });

There is no error. Just no item in DB ;(

Upvotes: 2

Views: 2907

Answers (1)

Sello Mkantjwa
Sello Mkantjwa

Reputation: 1915

You need to tell mongoose to create a new doc if one does not exist. You do this by specifying the upsert option as part of the 3rd parameter. Like so:

User.findOneAndUpdate(
        {userId:  userID}, 
        { $set: { "userAddress" : AddressObj} },
        {upsert:true, new:true},  //upsert to create a new doc if none exists and new to return the new, updated document instead of the old one. 
        function(err, doc){
            if(err){
                console.log("Something wrong when updating data!");
            }

            console.log(doc);
        });

Upvotes: 4

Related Questions