【问题标题】:Not able to perform operation with mongoose on db collection with few conditions在很少的条件下无法对 db collection 执行 mongoose 操作
【发布时间】:2018-03-25 04:37:47
【问题描述】:
我正在为 Mongo db 使用 Mongoose。我想执行一些操作。无法得到结果。
我有一个用户集合,其架构如下:
{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 除外),则什么也不做(不要更新或在集合中输入用户)并保留该用户未能在数据库中输入的值。
请帮忙。
【问题讨论】:
标签:
javascript
json
mongodb
mongoose
mongoose-schema
【解决方案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
}
})