繁体   English   中英

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

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

我正在使用 Expressjs、Mongodb 和 Mongoose 开发服务器。我需要将一个元素(一个字符串)推入“tweets”数组,该数组位于 object(朋友)内,而后者又位于“朋友”数组内一个“用户”Object 在“用户”集合中的文档。 这是我在 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
}

我需要先从“Users”数组中选择指定的用户名,然后访问该用户中的“friends”数组,然后选择正确的朋友 object,最后将推文推送到此数组中的 $position:0。 我试图实现这一点,如这段代码所示,我可以使用给定的 friendUsername 访问朋友 object

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

现在的问题是如何访问 $elemMatch 中的“tweets”数组并将 $position: 0 处的 req.body.tweet 推入其中?

这是我将如何解决您的问题,我首先会重新定义我定义模式的方式。

我的User架构如下所示

用户.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)

用户.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)

这假设每个用户都可以拥有推文并且一个User可以与另一个User成为朋友

现在,如果有人发推文,你可以做类似的事情

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 } })

现在,每当您请求用户时,他的所有朋友都会被引用,他们的所有推文也会被引用! 如果您想查看实际的推文,请使用类似.populate()的内容,这里是 .populate .populate() ) 的文档https://mongoosejs.com/docs/populate.html

请记住,只返回实际ids确实是一个很好的做法,您的前端会负责从其透视端点请求适当的对象。 如果您希望减少网络调用,那么前端会缓存数据。

如果以上方法没有帮助并且您仍然希望通过您的模式实现您的目标那么这样的事情应该有效(假设您的模式被称为User

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

注意:我省略了回调,因为它们与问题无关

暂无
暂无

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

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