簡體   English   中英

使用 mongoose 在 nodejs 后端寫入和檢索數據

[英]Using mongoose to write and retrieve data in nodejs backend

我更新了 MongoDb 和 Node.Js。

我應該檢查資產是否存在,然后(如果不存在)創建它。

這是資產模式

var Schema = mongoose.Schema;

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

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

檢查資產是否存在

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
                } 
            });
      }
  }

新建一個

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)
            } 
        })
    }
}

不管怎樣,我查了一下,這兩種方法似乎都行不通。 我以為這是一個連接問題,但連接有效。

我使用 MongoDB Cloud,這是連接字符串

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

集合資產

我錯過了什么? 兩種方法都正確嗎? 謝謝

您的方法的問題是您使它們async但以同步方式使用它們。

重構:

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

創建新資產時,您可以檢查是否存在具有給定名稱的資產:

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
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM