2013-10-11 53 views
0

我在一个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

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

因此,要么:

变化newRequest返回一个普通的对象,后来传递到new Request()电话,如果你需要将它添加到数据库中。

OR

在你main功能转tempReq到一个查询对象是这样的:

var query = tempReq.toObject(); 
delete query._id; 
Request.findOne(query, ...