如何从数组中创建用户并在mongoose中返回他们的id

How to create users from array and return their ids in mongoose?

本文关键字:mongoose 返回 id 他们的 用户 数组 创建      更新时间:2023-09-26

Service获取用户名数组,检查每个用户名是否存在(如果不存在则创建用户),并返回具有此类名称的用户id。我不知道怎么做,因为搜索和保存是异步的

下面的代码是用于查询集合以获得基于id的文档。如果它找到它返回文档,否则它可以为我们使用{upsert:true}插入文档。这是基本的代码示例遵循mongoose docs http://mongoosejs.com/docs/api.html

Model.findOneAndUpdate({_id:id},{upsert:true}, function(err, doc){
    if (err)  {
        console.log('if error occurs'); 
    } else {
        console.log('doc',doc) 
    }
});

我使用node js的async库。