Using mongoose to write and retrieve data in nodejs backend

58 Views Asked by At

im newer about MongoDb and Node.Js.

I should check if an Asset exists, and then (if not exist) create it.

This is the Asset schema

var Schema = mongoose.Schema;

var AssetSchema = new Schema({
    name: String,
    creationDate: { type: Date, default: Date.now },
}, {collection: 'Assets'})

var Asset = mongoose.model('Asset', AssetSchema)

Check if asset exists

async function assetExists(assetName, callback) {
    if(assetName){
        Asset.findOne({name: assetName}
            , function(err, asset){
                if(err){
                    callback(err, null);
                    console.log('Error on find asset '+assetName)
                } else {
                    callback(null, asset.name); //Using this I get the asset.name or undefined
                } 
            });
      }
  }

Create new one

async function addAsset(assetName, callback){
    if(assetName){
        var newAsset = new Asset({name: assetName})

        await newAsset.save( function(err, asset){
            if(err){
                callback(err, null);
                console.log('Error on add asset '+assetName)
            } 
        })
    }
}

Anyway I checked, and no one of these two methods seem to work. I thought it was a connection problem, but the connection works.

I use MongoDB Cloud, this is the connection string

mongodb+srv://<username>:<password>@<clustername>.4ny68c7.mongodb.net/?retryWrites=true&w=majority

collection Asset

What am i missing? Do both method are correct? Thanks

1

There are 1 best solutions below

0
On

The problem with your methods are you're making them async but using them in a synchronous way.

Refactored:

async function assetExists(assetName) {
  const asset = await Asset.findOne({name: assetName});
  return asset ? asset : false; // returns asset if exists otherwise false;
}

While creating a new Asset you can check if an Asset with given name exists or not:

async function addAsset(assetName) {
  try {
    const isAssetExisting = await assetExists(assetName); // re-using the above function
    if (!isAssetExisting) {
      const newAsset = new Asset({ name: assetName });
      return await newAsset.save() // returns newly created asset
    }
    return isAssetExisting; // otherwise returns existing asset
  } catch (err) {
    // Your way of handling error
  }
}