mongoose - 如何判断 Mongoose 对象在数组中是否有 ID?

标签 mongoose

如何确定文档的属性是否已具有另一个 ObjectId 的实例?我已经从数据库中获得了文档,所以我不想再次访问数据库?

示例:

var userSchema = new mongoose.Schema({
    email: { type: String, unique: true, lowercase: true },
    friends: [ type: mongoose.Schema.Types.ObjectId, ref: 'User' ]
});

而且,我已经有了用户文档:

var friendId = req.body.friendId;

User.findOne({ email: req.body.email }, function(err, user){
    if (!user){
        return res.status(400).send({ message: 'User not found' });
    } else {
        // DETERMINE IF 'friends' ARRAY ALREADY HAS THE friendId
        // ADD THE friendId IF IT DOES NOT EXIST
    }
}

我已经在 Schema 和 User 对象上尝试了所有我能想到的方法,但没有任何效果。

最佳答案

您提到您尝试过 indexOf(friendId) 但事实上,这就是如何做到这一点:

var friendId = req.body.friendId;

User.findOne({ email: req.body.email }, function(err, user){
    if (!user){
        return res.status(400).send({ message: 'User not found' });
    } else {
        if (user.friends.indexOf(friendId) === -1) {
            // friendId is not already in user.friends; add it
        } else {
            // friendId already exists
        }
    }
}

或者,根据您最终想要执行的操作,您可以通过使用 $addToSet 的单个更新来完成所有操作。将 friendId 添加到 friends 数组(仅当它尚不存在时):

User.update(
    { email: req.body.email },
    { $addToSet: { friends: friendId } },
    function(err, count){
        if (!count){
            return res.status(400).send({ message: 'User not found' });
        }
        ...
    }
);

此外,这可能只是一个拼写错误,但我必须将 userSchema 更改为以下内容才能使其有效:

var userSchema = new mongoose.Schema({
    email: { type: String, unique: true, lowercase: true },
    friends: [ { type: mongoose.Schema.Types.ObjectId, ref: 'User' } ]
});

关于mongoose - 如何判断 Mongoose 对象在数组中是否有 ID?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27591512/

相关文章:

mongodb - 如何在 Meteor 中使用 Mongoose?

node.js - cPanel Node.js 应用程序无法连接到 MongoDB Atlas 集群,但可以在 Heroku 上运行

node.js - 使用 promise 解析/拒绝对 Mongoose 验证进行单元测试

javascript - 如何合并 MongoDB 查找查询的输出?

node.js - Mongoose 聚合不支持 writeConcern

node.js - 更新 Mongoose 中的嵌套数组

javascript - 合并 2 个具有不同值类型的数组

javascript - 返回匹配字段数组的文档

javascript - 合并 Mongoose 中的两个对象

mongodb - 使用 NoSQL 文档存储对 RBAC 进行建模的策略