Home > Back-end >  Nodejs Mongoose still return fields if missing
Nodejs Mongoose still return fields if missing

Time:05-25

I just want mongoose to return exactly data event if that field missing from db

Items.find({}, {image1: 1, image2: 1, image3: 1})

Expected:

[
    {
        "_id": "zz",
        "image1": "link1",
        "image2": "link2",
        "image3": "link3"
    },
    {
        "_id": "zz",
        "image1": "link1",
        "image2": "",
        "image3": "link3"
    },
    {
        "_id": "zz",
        "image1": "",
        "image2": "",
        "image3": ""
    }
]

Currently:

[
    {
        "_id": "zz",
        "image1": "link1",
        "image2": "link2",
        "image3": "link3"
    },
    {
        "_id": "zz",
        "image1": "link1",
        "image3": "link3"
    },
    {
        "_id": "zz"
    }
]

Does mongoose already have ways to do or i have to manual map by fields?

CodePudding user response:

I am not sure but I think that is not possible, another solution could be adding a default value of null or "" for example, and for the existing documents you can use a simple script that runs through all the documents and check if the document does not have the field then it adds it with the default value.

require("../../db/mongoose");
const Item = require("../../models/item");

const migrate = async () => {
  const items = await Item.find({});
  for (item of items) {
    if (!item.image1 && item.image1 != "") {
      item.image1 = "";
    }

    await item.save();
  }

  console.log("Done migrating items data");
};

migrate();

CodePudding user response:

In this case you can add default in your schema. If you do this, an empty string is saved by default for that undefined fields.

const ItemSchema = new Schema({
image1: {type: String, default: ""},
image2: {type: String, default: ""},
image3: {type: String, default: ""}        
});

So you can simply find your Expected data.

db.collection.find({},
{
   image1: 1,
   image2: 1,
   image3: 1
 })

return

[
 {
   "_id": "6151c68149c45c0039c87f69",
   "image1": "link1",
   "image2": "link2",
   "image3": "link3"
 },
 {
   "_id": "6151c68149c45c0039c87f68",
   "image1": "link1",
   "image2": "",
   "image3": "link3"
  },
  {
   "_id": "6151c68149c45c0039c87f61",
   "image1": "",
   "image2": "",
   "image3": ""
   }
 ]

I hope this solution helps you.

  • Related