Mongoose,这个模型是否已经存在于该集合中

时间:2013-10-11 19:05:35

标签: mongodb mongoose

我在Node.js服务器上使用Mongoose将数据保存到MongoDB中。我想要做的是检查并查看集合中是否存在模型对象。

例如继承我的模特:

var ApiRequest = new Schema({
    route: String,
    priority: String,
    maxResponseAge: String,
    status: String,
    request: Schema.Types.Mixed,
    timestamp: { type: Date, default: Date.now }
});

这就是我想做的事情:

var Request = mongoose.model('api-request', ApiRequest);

function newRequest(req, type) {
    return new Request({
        'route' : req.route.path,
        'priority' : req.body.priority,
        'maxResponseAge' : req.body.maxResponseAge,
        'request' : getRequestByType(req, type)
    });
}

function main(req, type, callback) {
    var tempReq = newRequest(req, type);

    Request.findOne(tempReq, '', function (err, foundRequest) {
        // Bla bla whatever
        callback(err, foundRequest);
    });
}

我发现的重大问题是作为模型的tempReq具有_id变量和时间戳,该时间戳将与数据库中保存的时间戳不同。所以我想忽略这些领域,并通过其他一切进行比较。

作为一个注释我的实际模型有比这更多的变量因此我不想使用.find({param:val,....}).....而是想要使用现有的比较模型。

有什么想法吗?谢谢!

1 个答案:

答案 0 :(得分:1)

您需要使用普通JS对象而不是Mongoose模型实例作为查询对象(find的第一个参数)。

所以:

更改newRequest以返回普通对象,如果需要将其添加到数据库中,则稍后将其传递给new Request()

OR

main函数中将tempReq转换为如下查询对象:

var query = tempReq.toObject();
delete query._id;
Request.findOne(query, ...
相关问题