在mongoose schema nodejs中按ObjectId搜索

时间:2021-01-12 02:34:01

I am using mongoose with nodejs . I have item schema and user schema given below.

我正在使用nodejs的mongoose。我有下面给出的项目架构和用户架构。

var userSchema = new Schema({
  email: { type: String, required: true, unique: true },
  password: { type: String, required: true },
  items : [{ type: Schema.Types.ObjectId, ref: 'Item' }]
});

var itemSchema = new Schema({
  name: { type: String, required: true },
  _owner : { type: Schema.Types.ObjectId, ref: 'User' }
});

I am trying to find item by user id(_owner in item schema).

我试图按用户ID(项目架构中的_owner)查找项目。

I have tried to find directly

我试图直接找到

var uid = req.decoded._id;
var item = Item.findOne({"_owner": uid});
console.log(item.name);   // undefined

By searching similar I found that id needs to be in ObjectId object so I tried

通过搜索类似我发现id需要在ObjectId对象中,所以我尝试了

var uid = new mongoose.Types.ObjectId(req.decoded._id);
var item = Item.findOne({"_owner": uid});
console.log(item.name);   // undefined 

In both the cases item.name is undefined .Note that I have rechecked the value of req.decoded._id(by printing) with the db so it not undefined and present in db.

在两种情况下,item.name都是未定义的。注意我已经使用db重新检查了req.decoded._id(通过打印)的值,因此它没有未定义并存在于db中。

Is there anything I am doing wrong?

有什么我做错了吗?

1 个解决方案

#1


2  

Model.findOne is an async call. It doesn't return the doc, it passes it to a callback function that you need to provide as a second parameter.

Model.findOne是一个异步调用。它不返回doc,它将它传递给您需要提供的第二个参数的回调函数。

var uid = req.decoded._id;
var item = Item.findOne({"_owner": uid}, function(err, item) {
    console.log(item.name);
});

#1


2  

Model.findOne is an async call. It doesn't return the doc, it passes it to a callback function that you need to provide as a second parameter.

Model.findOne是一个异步调用。它不返回doc,它将它传递给您需要提供的第二个参数的回调函数。

var uid = req.decoded._id;
var item = Item.findOne({"_owner": uid}, function(err, item) {
    console.log(item.name);
});