将对象ID推送到嵌套数组MongoDB / Mongoose

时间:2018-10-23 21:57:40

标签: node.js angular mongodb express mongoose

所以我正在尝试为正在使用的应用程序做一个简单的 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在嵌套数组方面没有很好的文档。

2 个答案:

答案 0 :(得分:1)

尝试这种方式

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)

答案 1 :(得分: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');
    });
  });      
})
相关问题