Reputation: 1774
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
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