1

Assume that I have a document in database which has the following structure;

id: 1,
name: alex,
age: 21

There are some updates in client side and the same document with id:1 returns as;

id: 1,
name: alex,
age: 21,
location: usa

where a new field location is added.

I want to update the document in database. I want to add this new inserted field but I couldn't find out how can I handle this situation. Because location is not static, it can be surname, job and so on. So new inserted fields are dynamic and I don't know in advance.

If the field location was static, I could write a query as;

db.collection("user").updateOne( {id: 1},
                     {$set: {name: "alex", age: "21", location: "usa"}}, function(err, result){
     if(err){} 
     else{}
});

But now, how can I update the document with this newly added fields?

2
  • So your question seems to be more about how do you query, rather than how do you update? inserting the document is no different than any other time unless you're enforcing schemas via mongoose or similar. Commented Sep 29, 2016 at 14:34
  • But I was setting the fields as in the example. Now, how can I set them? I don't know the fields in advance. I couldn't update document with id :1. Commented Sep 29, 2016 at 14:40

1 Answer 1

3

If you are saying that you have an updated object:

id: 1,
name: alex,
age: 21,
location: usa

then I assume that you have some object that has a value of:

{
  id: 1,
  name: 'alex',
  age: 21,
  location: 'usa'
}

e.g. as a result of parsing this JSON sent from the client:

{
  "id": 1,
  "name": "alex",
  "age": 21,
  "location": "usa"
}

If you have that object in a variable called object then all you have to do is:

db.collection("user")
  .updateOne({id: object.id}, {$set: object}, function (err, result) {
    if (err) {
      // handle success
    } else {
      // handle success
    }
});

But most likely you will need to use _id instead of id:

db.collection("user")
  .updateOne({_id: object._id}, {$set: object}, function (err, result) {
    if (err) {
      // handle success
    } else {
      // handle success
    }
});

If you want to be able to remove properties as well then maybe even:

db.collection("user")
  .replaceOne({_id: object._id}, object, function (err, result) {
    if (err) {
      // handle success
    } else {
      // handle success
    }
});

I wouldn't recommend putting data into the database without at least some sort of validation but it's possible to do what you're asking about in the way shown above.

For more info see:

in the Introduction to MongoDB in Node.js.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.