[英]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.