NodeJS 访问mongoose方案单元并用作对象

ctrmrzij  于 5个月前  发布在  Node.js
关注(0)|答案(1)|浏览(57)
const userSchema = new Schema({
  username: {
      type: String,
      unique: true //< Adds a unique index
   },
  password: String,
  email: {
      type: String,
      unique: true //< Adds a unique index
   },
  categoryLinks: { type:Array, "default": [] },
  links : { type : Array , "default" : [] },
  imagelink: String,
  plan: String,
  bakiye: Number,
});

字符串
我想让categoryLinks作为一个数组,它包含多个相同类型的对象,但在mongoose上却没有做到这一点。
我试着(举例说明):

categoryLinks: {
    type: {Array, default: [ {"label": String, "link":String, "links": []}, {/*more of the same type..*/} ] }, 
}


所以当我找到一个使用findOne的用户时,我可以访问categoryLinks

await userModel.findOne({
   username: req.session.username
 }).then(
   (user)=>{
   for(var k = 0; k < user.categoryLinks.length; k++){
     console.log(user.categoryLinks[k].links.label + " is now iterating category");
     for(var i=0; i < user.categoryLinks[k].links.length; i++){
       //update user.categoryLinks[k].links... by using push() or findOneAndUpdate??
     }
     //user.categoryLinks.links.forEach()  or can use for each
   }
   
 });


我想访问它,因为我正在访问一个JavaScript对象与对象键像这样。我失败了,
然后可能通过标签查找索引并推送到其数组(或者删除元素)来更新

await userModel.findOneAndUpdate(filter, {user.categoryLinks[filter.k].links : user.categoryLinks[filter.k].links.push(newLink)});


如果我想更新对象内部的数组,我可以直接使用push吗?
所以基本上,我有一个数组,它包含的对象也包含数组。我如何使用findOneAndUpdate()这样的函数来更新它?我可以使用push()方法吗?

nfg76nw0

nfg76nw01#

我认为最好的选择是使用Subdocuments
在这种方法中,您为将存储在categoryLinks中的对象定义了一个模式。您可以获得定义良好的模式的所有验证好处,但这意味着如果您有大量对象,文档可能会变得无法控制。我的意思是,如果您的应用程序容量很大,并且每个用户都要处理数万个categoryLinks对象,那么您可以看到这将如何使数组在存储方面非常大。MongoDB有一个标准的16MB文档限制。对于大多数应用程序来说,这是可以的。
定义categoryLinkSchema

const categoryLinkSchema = new mongoose.Schema({
  label: String,
  link: String,
  links: { type: Array, default: [] },
});

字符串
categoryLinkSchema设置为categoryLinks类型的值:

const userSchema = new Schema({
  username: {
      type: String,
      unique: true //< Adds a unique index
   },
  password: String,
  email: {
      type: String,
      unique: true //< Adds a unique index
   },
  categoryLinks: [categoryLinkSchema], //< Use the new schema here
  //...
  //...
});


现在,当你想向categoryLinks数组添加一个对象时,你可以这样做:

app.post('/user/categories', async (req, res, next) => {
   /* req.body = { 
         label: 'New Label',
         link: 'www.google.com', 
         links: ['Red', 'Green'] 
      };
   */
   try{
      const newCat = { 
         label: req.body.label,
         link: req.body.link,
         links: req.body.links
      }
 
      const user = await userModel.findOneAndUpdate({
            email: "[email protected]"
         },
         {
            $push: {
               categoryLinks: newCat
            }
         }, 
         { new: true }
      );
      return res.status(201).json({
         message: 'Added to categoryLinks.'
      })
   }catch(err){
      console.log(err);
      return res.status(500).json({
         message: 'Error on server'
      })
   }
});

相关问题