Mongodb Mongoose,集合中是否已经存在此模型
我在Node.js服务器上使用Mongoose将数据保存到MongoDB中。我要做的是检查集合中是否已经存在模型对象 例如,以下是我的模型:Mongodb Mongoose,集合中是否已经存在此模型,mongodb,mongoose,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
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,…..})。。。。。相反,我想使用现有的模型进行比较
有什么想法吗?谢谢 您需要使用普通JS对象而不是Mongoose模型实例作为查询对象(查找
的第一个参数)
因此,要么:
更改newRequest
以返回普通对象,然后如果需要将其添加到数据库中,将其传递到newRequest()
调用中
或
在main
函数中,将tempReq
转换为如下查询对象:
var query=tempReq.toObject();
删除查询。\u id;
Request.findOne(查询。。。