Chenya Zhang Chenya Zhang - 3 months ago 11
Node.js Question

How to check if elements in Embedded Document is empty or not? Node.js & Mongodb

I want to check if elements in Embedded Document is empty or not. For example:

if (files.originalFilename === 'photo1.png') {
user.update(
{
userName: userName
},
{ $set: { "competitorAnalysisPhoto.photo1" : files.path } }
);
console.log('Got photo1!');

// save the user
user.save();
}


Currently, I cannot update the field "photo1" if it is empty. How can I check if it is empty or not?

I try to use:

if (user.competitorAnalysisPhoto.photo1 == null) {
console.log('Photo1 is null!');
user.competitorAnalysisPhoto.push({
photo1: files.path
});
} else {
console.log('Photo1 is not null!');
user.update(
{
userName: userName
},
{ $set: { "competitorAnalysisPhoto.photo1" : files.path } }
);
}


However, it is always null no matter photo1 exists or not, printing out "undefined".

Answer

Have you tried using 'upsert'?

if (files.originalFilename === 'photo1.png') {
            user.update(
                {
                    userName: userName
                },
                { $set: { "competitorAnalysisPhoto.photo1" : files.path } },
                { upsert: true }
            );
            console.log('Got photo1!');

            // save the user
            user.save();
        }