简体   繁体   English

为什么 Model.find 不在变量中存储数据?

[英]Why Model.find is not storing data in variable?

Im trying to create and save new model instances and assign a unique id to each of them in my MONGODB Atlas database.我正在尝试创建和保存新的 model 实例,并在我的 MONGODB Atlas 数据库中为每个实例分配一个唯一的 ID。 To do this Im trying to get data from my models using Model.find() and store it in a variable where I can loop through the array and check if id assigned already exists in the collection objects.为此,我尝试使用 Model.find() 从我的模型中获取数据并将其存储在一个变量中,我可以在其中循环遍历数组并检查分配的 id 是否已存在于集合对象中。 I can succesfully log the collection but it seems that I cant store the colletion array in a variable.我可以成功记录集合,但似乎我无法将集合数组存储在变量中。

Whenever I try to console.log(dbData) I get undefined, should I also have to call model.find in a get request that points to the form action path whenever a form is submited?每当我尝试 console.log(dbData) 我得到未定义时,我是否还必须在提交表单时在指向表单操作路径的获取请求中调用 model.find?

 var formModel=mongoose.model("Form-Model", newFormSchema)


    let dbData =formModel.find({}, function(err,data){
        if(err) console.error(err)
        console.log(data)
        return data
    })

        let rndm=2
        function isUnique(rndm){
          let unique=dbData.some(element=>element.id===rndm)
          while(unique){
            rndm=Math.floor(Math.random()*10000)
            unique=arr.some(element=>element.id===rndm)
          }

         return rndm
        }


    app.post("/form-data",function(req,res){

        console.log(req.body)
        var newForm= new formModel({
            output:req.body.output,
            id:isUnique(rndm)
        })
        newForm.save()
        res.send("new user submited")
        res.end()
    })

EDIT//////编辑//////

I saw somewhere else that you need either a promise or async/await to wait for model.find to finish getting objects array but when console.logging(dbData) I get promise pending,我在其他地方看到您需要 promise 或 async/await 来等待 model.find 完成获取对象数组但是当 console.logging(dbData) 我得到 promise 挂起时,

async function dbData() {
try{
let dbData= await formModel.find({})
return dbData
    }
catch(err){
console.log(err)
    }

}
console.log(dbData()) // returns Promise { <pending> }

use.then(function(res) //execude code with returned result from async function here ) use.then(function(res) //执行代码,返回结果来自异步 function here )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM