gpt4 book ai didi

node.js - 检查文档中的字段

转载 作者:太空宇宙 更新时间:2023-11-04 02:43:07 24 4
gpt4 key购买 nike

假设我有以下架构

 var userSchema = new Schema({
name : String
});

var User = mongoose.model('User',userSchema);

编辑:如果用户尝试更新不存在的字段,我需要抛出异常。我的问题是如何检查更新文档中不存在更新字段。这是我需要的一个小例子:

  app.post('/user/update/:id', function (req, res) {
var field = req.param('field'),
value = req.param('value'),
id = req.param('id');

User.findOne({_id: id},function(err, user){
if(err) throw err;

if (user) {

user[field] = value; // Here is I need to check that field is exists
// in user schema. If does't I have to throw
// an execption.

user.save(function (err){
return res.send(200);
});
}
})
});

最佳答案

尝试将 $exists 添加到 update() 的查询参数中。这将允许您仅在某个字段存在(或不存在)时更新文档。

http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24exists

关于node.js - 检查文档中的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11171896/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com