【问题标题】:Pushing Object ID to Nested Array MongoDB/Mongoose将对象 ID 推送到嵌套数组 MongoDB/Mongoose
【发布时间】:2019-03-28 05:49:42
【问题描述】:

所以我正在尝试为我正在开发的应用程序做一个简单的 Thumbs Up 系统,但我在将用户 ID 推送到 likes 数组时遇到问题。这是我的代码的样子:

房间架构

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const classroomSchema = Schema({
    clName: String,
    clPosts: [{
        title: String,
        mssg: String,
        date: String,
        imageurl: String,
HERE==> likes: [{type: Schema.Types.ObjectId, ref: 'User'}] 
    }]
})

const Classroom = mongoose.model('Classroom', classroomSchema)
module.exports = Classroom

路由器

router.put('/put/classroom/post/like/:id', (req, res, next) => {
    var data = data = req.body
    Classroom.findByIdAndUpdate(
        {
            _id: req.params.id,
            "clPosts": { _id: data.post }
        },
        { $push: { "clPosts.$[outer].likes": [data.user] } },
        { "arrayFilters": [{ "outer._id": data.post }] }
    ).then((room) => {
         console.log("Done"); 
         res.json(room);
    }).catch(next)
})

我已经尝试在 SO 上遵循其他建议,但我不确定我的某些配置是否不正确,或者是否有更好的方法将对象推送到嵌套数组中。

基本设置是,有一个包含教室对象的教室集合。在教室里,有posts 对象数组,在里面,有一个likes 数组。这个想法是每当有人喜欢该帖子时,它将该用户的 ObjectID 保存到数组中,然后我用它来计算有多少喜欢,等等......

如果需要更多详细信息,请告诉我,MongoDB 没有关于嵌套数组的良好文档。

【问题讨论】:

    标签: node.js angular mongodb express mongoose


    【解决方案1】:

    clPosts 是一个子文档。您通过_id -> "clPosts": { _id: data.post } 查询帖子,但我相信,查询应该是这样的:"clPosts._id": { _id: data.post_id }

    由于您使用mongoose,您可以这样做:

    const mongoose = require('mongoose');
    const Schema = mongoose.Schema;
    
    const ClassRoomPostsSchema = new Schema({
        title: String,
        mssg: String,
        date: String,
        mageurl: String,
        likes: [] // you will push ids here or else, if you need to store more data, e.g. date/time when like was given, create a schema for Likes e.g. likes: [likeSchema.schema]
    })
    
    const ClassRoomSchema = new Schema({
        clName: String,
        clPosts: [ClassRoomPostsSchema.schema]
    })
    

    然后在你的代码中:

    router.put('/put/classroom/post/like/:id', (req, res, next) => {
      ClassRoom.findOne({_id: req.params.id}, function(err, room) {
        if (err) return next(err);
    
        if (!room) return res.status(404).send('Classroom not found');
    
        //Find a post by id
        let post = ClassRoom.clPosts.id(data.post); // -> data.post_id
    
        if (!post) return res.status(404).send('Post not found');
    
        // Here you can push ids, but what is the idea behind? Maybe it makes more sense to count likes or push Like schemas (subdocument) to the array, e.g. post.likes.push(new Like(data));        
        post.likes.push();
    
        room.save(function(err) {
          if (err) return serverValidationError(req, res, err);
          res.status(200).send('success');
        });
      });      
    })
    

    【讨论】:

    • 您好,感谢您的回复,我意识到我将 _id 放在了错误的位置,但我决定按照您的建议为喜欢创建一个新模式,我没有考虑添加额外的数据之类的。我不再需要将对象推送到嵌套数组中
    【解决方案2】:

    试试这个方法

    Classroom.findByIdAndUpdate(
            {
                _id: req.params.id,
                "clPosts._id": data.post
            },
            { $push: { "clPosts.$.likes": [data.user] } }
        ).then((room) => {
             console.log("Done"); 
             res.json(room);
        }).catch(next)
    

    【讨论】:

    • 您好,感谢您的回复,我意识到我将 _id 放在了错误的位置,但是在尝试了您的解决方案后,我继续收到错误:[ERROR] The positional operator did not find the match needed from the query.
    猜你喜欢
    • 2020-07-08
    • 1970-01-01
    • 2019-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多