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
What am i missing? Do both method are correct? Thanks
The problem with your methods are you're making them
async
but using them in a synchronous way.Refactored:
While creating a new Asset you can check if an Asset with given name exists or not: