无法在条件很少的情况下使用猫鼬对数据库集合执行操作

Not able to perform operation with mongoose on db collection with few conditions

我正在为 Mongo 数据库使用 Mongoose。我想执行一些操作。无法得到结果。

我有一个集合 USERS,其架构如下:

{username: 'user1', id: 1, lastName: 'ln1' }
{username: 'user2', id: 0, lastName: 'ln2' }

ID 可以是 0,1,2 或 3

我想输入一个具有这些条件的新对象:

请帮忙。

我使用了 promise 库,但你也可以使用回调

假设:您想在用户模型上工作

 User.findOne({username:"USERNAME"}).exec()
    .then((result)=>{
      if(result){
          if(result.id == 1){
         //update result object and then save it
           result.lastName="abc";
           result.save(); // it will update your result
            }else{
           console.log('failed to enter in the db.')  
           }
        }else{
          User(userObject).save(); // it will create new entry
        }

})