Mongodb 如何为ID不在数组中的项编写Mongoose查询
我有两种模式:Mongodb 如何为ID不在数组中的项编写Mongoose查询,mongodb,mongoose,Mongodb,Mongoose,我有两种模式:事件和人 schemas.event = new mongoose.Schema({ eventId: Number, name: {type: String}, size: Number, location: {type: String}, date: {type: Date}, people: [{type: mongoose.Schema.Types.ObjectId, ref: models.Person}],
事件
和人
schemas.event = new mongoose.Schema({
eventId: Number,
name: {type: String},
size: Number,
location: {type: String},
date: {type: Date},
people: [{type: mongoose.Schema.Types.ObjectId, ref: models.Person}],
note: {type: String}
});
和人
schemas.person = new mongoose.Schema({
firstname: {type: String},
lastname: {type: String},
age: Number,
email: {type: String},
gender: {type: String}
});
给定某个事件,我想使用Mongoose进行查询,以查找尚未注册此事件的所有人员
差不多
models.Person.find({not in event.people});
对我来说,棘手的事情是,event.people
不是一个ID数组,而是一个看起来像
[
{
"$oid": "558ced061d35bd072e7b5825"
},
{
"$oid": "558ced061d35bd072e7b58a0"
},
{
"$oid": "558ced061d35bd072e7b58c6"
}
],
有什么方法可以简单地进行此查询吗?查看以下运算符:
$not - http://docs.mongodb.org/manual/reference/operator/query/not/
$in - http://docs.mongodb.org/manual/reference/operator/query/in/
$nin - http://docs.mongodb.org/manual/reference/operator/query/nin/
首先,您需要使用本机JavaScript方法创建ObjectId的数组,该方法创建一个新数组,其结果是在该数组中的每个元素上调用提供的函数:
var mongoose = require("mongoose");
var arr = event.people.map(function(item){ return mongoose.Types.ObjectId(item["$oid"])});
然后,您可以使用它作为运算符表达式来查询集合:
models.Person.find({"_id": { "$nin": arr}}).exec(callback);
仅供参考:您的答案与其说是答案,不如说是评论。
mongoose.Types.ObjectId(item[“$oid”])
似乎返回了一个全新的oid
,这不是我想要的。我想我将只返回项[“$oid”]
。。。编辑:但它返回null
…如果直接映射它而不强制转换到ObjectId
event.people.map(函数(项){return item[“$oid”]}),该怎么办代码>?是的,它现在工作了。我犯了一个错误,我以前是填充他们。。。不管怎么说,它现在起作用了!谢谢