简体   繁体   English

如何将元素推入 Mongoose 中另一个数组中的 object 中的数组?

[英]How to push an element into an array inside an object inside another array in Mongoose?

I am developing a server using Expressjs, Mongodb and Mongoose. I need to push an element (a string) into the "tweets" array which is inside an object (a friend) which is in turn inside the "friends" array which is inside a "user" Object which document in the "users" collection.我正在使用 Expressjs、Mongodb 和 Mongoose 开发服务器。我需要将一个元素(一个字符串)推入“tweets”数组,该数组位于 object(朋友)内,而后者又位于“朋友”数组内一个“用户”Object 在“用户”集合中的文档。 Here is an example of how my documents in the Mongodb collection looks like:这是我在 Mongodb 集合中的文档的示例:

{
    "loggedIn": true,
    "_id": "5f91ef0ce75d3b1d40539da0",
    "username": "username",
    "email": "a@h.com",
    "password": "$2a$10$9krWS9Kq5024lRTexqaweePrn8aughepqTkaj3oA48x0fJ2ajd79u",
    "dateOfBirth": "2002-12-07",
    "gender": "male",
    "friends": [
        {
            "tweets": [],
            "_id": "5f91effae75d3b1d40539da7",
            "username": "Jonas"
        },
        
    ],
    "__v": 0
}

I need to pick the specified username from the "Users" arrary first and then access "friends" array within this user and then pick the right friend object and finally push the tweet on $position: 0 in this array.我需要先从“Users”数组中选择指定的用户名,然后访问该用户中的“friends”数组,然后选择正确的朋友 object,最后将推文推送到此数组中的 $position:0。 II tried to achieve that as shown in this code and I could access the friend object with the given friendUsername我试图实现这一点,如这段代码所示,我可以使用给定的 friendUsername 访问朋友 object

await Users.updateOne(
      { username: req.params.username },
      {
        $push: {
          friends: {
            $elemMatch: {
              username: req.params.friendUsername,
            },
          },
        },
      }
    );

And now the question is how to access the "tweets" array inside $elemMatch and push the req.body.tweet at $position: 0 into it?现在的问题是如何访问 $elemMatch 中的“tweets”数组并将 $position: 0 处的 req.body.tweet 推入其中?

Here is how I would solve your issue, I first would re-define the way I am defining schemas.这是我将如何解决您的问题,我首先会重新定义我定义模式的方式。

My User schema would look something like the following我的User架构如下所示

User.js用户.js

const mongoose = require('mongoose')

const UserSchema = mongoose.Schema({
 ...
 friends: {
    type: [{
       type: mongoose.Schema.Types.ObjectId,
       ref: 'User'
    }],
    required: true,
    default: []
  },
  tweets: {
    type: [{
      type: mongoose.Schema.Types.ObjectId,
      ref: 'Tweet'
    }],
    required: true,
    default: []
  },
 ...
}, {timestamps: true})

module.exports = mongoose.model('User', UserSchema)

User.js用户.js

const mongoose = require('mongoose')

const TweetSchema = mongoose.Schema({
 ...
 text: {
    type: String,
    required: true
  },
 tweeter: {
    type: mongoose.Schema.Types.ObjectId,
    required: true,
    ref: 'User'
 },
 likes: {
    type: [{
      type: mongoose.Schema.Types.ObjectId,
      ref: 'User'
    }],
    required: true,
    default: []
  },
 ...
}, {timestamps: true})

module.exports = mongoose.model('Tweet', TweetSchema)

This assumes that every user can have tweets and that a User can be friend with another User这假设每个用户都可以拥有推文并且一个User可以与另一个User成为朋友

And now if someone tweets something you can do something like现在,如果有人发推文,你可以做类似的事情

const Tweet = require('./Tweet.js')
const User = require('./User.js')

let tweet = new Tweet({
    text: "My first tweet!",
    tweeter: "ID Of user who is posting the tweet"
})

tweet.save()

// Now update the user who tweeted
User.findOneAndUpdate()
User.updateOne({ _id: "ID Of user who is posting the tweet" }, { $push: { tweets: tweet._id } })

and now whenever you request a user all of his friends will be referenced and all of their tweets will also be referenced!现在,每当您请求用户时,他的所有朋友都会被引用,他们的所有推文也会被引用! if you want to see the actual tweets then use something like .populate() here are the docs for .populate() https://mongoosejs.com/docs/populate.html如果您想查看实际的推文,请使用类似.populate()的内容,这里是 .populate .populate() ) 的文档https://mongoosejs.com/docs/populate.html

Keep in mind is really a good practice to only return the actual ids and your frontend takes care of requesting the appropriate objects from their perspective endpoints.请记住,只返回实际ids确实是一个很好的做法,您的前端会负责从其透视端点请求适当的对象。 And if you wish to reduce.network calls then the frontend would cache the data.如果您希望减少网络调用,那么前端会缓存数据。

If the above doesn't help and you still would like to achieve your goal with your schemas then something like this should work (assuming your schema is called User )如果以上方法没有帮助并且您仍然希望通过您的模式实现您的目标那么这样的事情应该有效(假设您的模式被称为User

let tweetObj = {}
User.updateOne({_id: 'your userid'}, {$push: {"friends.$.tweets": tweetObj}})

NOTE: I have omitted callbacks as they are irrelevant to the question注意:我省略了回调,因为它们与问题无关

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

相关问题 如何在猫鼬的数组中推送子文档? - How to push a sub document inside an array in mongoose? 如何将一个数组推入另一个数组内部的对象中? - How to push an array into an Object which is inside of another array? 如何填充数组内部的 object 和 mongoose 中的另一个数组中的所有用户字段 - How to populate all the user fields which is inside an object inside of an array and another array in mongoose 我如何将 object 推入 object 内的数组,该数组也在另一个数组内 - How do i push an object into an array which is inside an object which is also inside an another array 推送另一个数组中每个对象内的每个对象的元素 - push elements of each object inside each object inside another array 如何在猫鼬中查询对象数组内的值 - how to query value inside of object array in mongoose 如何在 mongoose 的数组中返回匹配的 object - How to return a matched object inside an array in mongoose 如何在猫鼬的对象数组中搜索对象? - how to search an object inside an array of objects in mongoose? JavaScript:如何在数组中的对象内引用数组并将其推入其中? - JavaScript: How to reference an array inside an object inside an array and push something to it? 如何推送到对象内部的数组,MongoDB 的数组内部? - How do you push to an array inside of an object, inside of an array with MongoDB?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM