0

I make a simple demo of MongoDB in node js .

first I save my document like this which is working fine .

{
"_id": "5d984cf947cd7301dab539be",
"tmObj": {
"a1": "N",
"a2": "N",
"a3": "N"
},
"__v": 0
}

now I want to update one attribute from my collection

example data is

const data = {
      a1: "Y"
    };

here is my code

https://codesandbox.io/s/objective-minsky-bqeil

app.get("/saveData", async (req, res, next) => {
  try {
    const data = {
      tmObj: {
        a1: "N",
        a2: "N",
        a3: "N"
      }
    };
    console.log("before save");
    let blog = new BlogPostModel(data);
    let saveBlog = await blog.save(data); //when fail its goes to catch
    return res.send(saveBlog);
  } catch (error) {
    console.log(error);
    return res.status(400).send(error);
  }
});

app.get("/update", async (req, res) => {
  try {
    const data = {
      a1: "Y"
    };
    let filterBlog = await BlogPostModel.find({});
    //when fail its goes to catch
    console.log(filterBlog); //when success it print.
    res.send(filterBlog);
  } catch (error) {
    console.log(error);
  }
});

any update?

user944513
  • 12,247
  • 49
  • 168
  • 318
  • What exactly do you want to update? `a1` field? – Daniyal Lukmanov Oct 05 '19 at 08:07
  • yes.!! I want to update `a1` – user944513 Oct 05 '19 at 08:11
  • then use `myCollection.updateOne({}, {'tmObj.a1': data.a1})` – Daniyal Lukmanov Oct 05 '19 at 08:46
  • Please note that the **only** reason the code `myCollection.updateOne({}, {'tmObj.a1': data.a1})` works is because Mongoose automatically adds the [`$set`](https://docs.mongodb.com/manual/reference/operator/update/set/) operator for you. The real things you should be *learning* are usage of `$set` and the usage of ["dot notation"](https://docs.mongodb.com/manual/core/document/#dot-notation) – Neil Lunn Oct 07 '19 at 02:04

1 Answers1

0

Here is the answer codesandbox

As you mentioned in comments that there will be only one document in the collection then you can use an empty query. To update and get the document back you can use findOneAndUpdate:

app.get("/update", async (req, res) => {
  try {
    const data = {
      a1: "Y"
    };
    let filterBlog = await BlogPostModel.findOneAndUpdate(
      {},
      { "tmObj.a1": data.a1 }
    );
    //when fail its goes to catch
    console.log(filterBlog); //when success it print.
    res.send(filterBlog);
  } catch (error) {
    console.log(error);
  }
});

To avoid deprecation warning you should add an option { useFindAndModify: false } in mongoose.connect.

Daniyal Lukmanov
  • 1,149
  • 10
  • 21