无法在条件很少的情况下使用猫鼬对数据库集合执行操作
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
我想输入一个具有这些条件的新对象:
- 如果用户名存在且 ID 为 1,则更新详细信息。
- 如果用户名不存在,则创建一个新条目,无需检查 ID。
- 如果用户名存在且 id 为 0,2 或 3(1 除外)则什么都不做(不更新或在集合中输入用户)并保留该用户未能在数据库中输入的值.
请帮忙。
我使用了 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
}
})
我正在为 Mongo 数据库使用 Mongoose。我想执行一些操作。无法得到结果。
我有一个集合 USERS,其架构如下:
{username: 'user1', id: 1, lastName: 'ln1' }
{username: 'user2', id: 0, lastName: 'ln2' }
ID 可以是 0,1,2 或 3
我想输入一个具有这些条件的新对象:
- 如果用户名存在且 ID 为 1,则更新详细信息。
- 如果用户名不存在,则创建一个新条目,无需检查 ID。
- 如果用户名存在且 id 为 0,2 或 3(1 除外)则什么都不做(不更新或在集合中输入用户)并保留该用户未能在数据库中输入的值.
请帮忙。
我使用了 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
}
})