【问题标题】:How to push an element into an array inside an object inside another array in Mongoose?如何将元素推入 Mongoose 中另一个数组内的对象内的数组中?
【发布时间】:2021-02-07 00:57:16
【问题描述】:

我正在使用 Expressjs、Mongodb 和 Mongoose 开发服务器。我需要将一个元素(一个字符串)推入一个对象(一个朋友)内的“tweets”数组中,该数组又位于一个“用户”对象内的“朋友”数组内,该对象在“用户”中记录收藏。这是我在 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”数组,然后选择正确的朋友对象,最后将推文推送到此数组中的 $position:0 上。我试图实现这一点,如这段代码所示,我可以使用给定的朋友用户名访问朋友对象

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

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

【问题讨论】:

    标签: javascript database mongodb mongoose mongoose-schema


    【解决方案1】:

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

    我的 User 架构如下所示

    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)
    
    

    User.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() https://mongoosejs.com/docs/populate.html 的文档

    请记住,只返回实际的ids 确实是一个好习惯,并且您的前端会负责从它们的透视端点请求适当的对象。如果你想减少网络调用,那么前端会缓存数据。

    如果上述方法没有帮助,并且您仍然希望通过架构实现目标,那么这样的事情应该可以工作(假设您的架构称为 User

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-11-14
      • 1970-01-01
      • 1970-01-01
      • 2020-02-08
      • 1970-01-01
      • 2019-12-22
      • 1970-01-01
      • 2020-12-04
      相关资源
      最近更新 更多