简体   繁体   English

在子文档MongoDB中检索数组

[英]Retrieve Array in Subdocument MongoDB

I have a Users model structure somewhat like this: 我有一个类似于以下的Users模型结构:

const userSchema = new mongoose.Schema({
  email: { type: String, unique: true },
  password: String,

  todosDo: [models.Do.schema],
}

And the child "Do" schema somewhat like this (in a different file): 子“ Do”模式有点像这样(在另一个文件中):

const doSchema = new mongoose.Schema({
  name: {type: String, default : ''},
  user: {type: mongoose.Schema.ObjectId, ref: 'User'},
  createdAt: {type : Date, default : Date.now}
});

And I'm trying to figure out how to retrieve the todosDo array for the signed in user. 我正在尝试找出如何为已登录用户检索todosDo数组。 This is what I've got so far: 到目前为止,这是我得到的:

// Get all "Do" todos from DB
// Experimenting to find todos from certain user
  User.findById(req.user.id, function(err, user){
    if(err){
        console.log(err);
    } else {
      doTodos = user.todosDo, // this obviously doesn't work, just an idea of what I was going for
      console.log(doTodos); 
      finished();
    }
  });  

Am I referencing the child/parent wrong or am I just not retrieving the array right? 我是错误地引用了孩子/父母,还是我没有正确检索数组? Any help is greatly appreciated! 任何帮助是极大的赞赏!

As far I guess you may want to edit as raw js objects so you need to use lean() function. 据我所知,您可能希望将其编辑为原始js对象,因此需要使用lean()函数。 without using lean() function user is mongoose object so you can't modify it. 如果不使用lean()函数,则用户为猫鼬对象,因此无法对其进行修改。

can try this one: 可以试试这个:

User.findById(req.user.id)
  .lean()
  .exec(function (err, user) {
    if(err){
      console.log(err);
      return res.status(400).send({msg:'Error occurred'});
    } 
    if(!user) {
      return res.status(400).send({msg:'User Not found'});
    }

    doTodos = user.todosDo;
    console.log(user.todosDo); // check original todos
    console.log(doTodos);
    return res.status(200).send({doTodos : doTodos }); // return doTodos 

  });

and to refer child schema in parent schema from different model you can access a Model's schema via its schema property. 并在不同模型的父模式中引用子模式 ,则可以通过其schema属性访问模型的模式。

say in doSchema.js file doSchema.js文件中说

const doSchema = new mongoose.Schema({
  name: {type: String, default : ''},
  user: {type: mongoose.Schema.ObjectId, ref: 'User'},
  createdAt: {type : Date, default : Date.now}
});
module.exports = mongoose.model( 'DoSchema', doSchema );

in user.js file user.js文件中

var DoModel = require('./doSchema');// exact path
const userSchema = new mongoose.Schema({
  email: { type: String, unique: true },
  password: String,

  todosDo: [DoModel.schema],
}

Thanks for your help everybody! 感谢大家的帮助! My problem was that I needed to push all the newly created todos in the post route to todosDo, so then I could retrieve them at the get route. 我的问题是我需要将发布路线中的所有新创建的待办事项推送到todosDo,这样我才能在get路线中检索它们。 Everything's working now! 现在一切正常!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM