无法使用猫鼬findOneAndUpdate()推送到数组

时间:2018-09-17 05:39:15

标签: mongoose graphql

我的 dbUsers 集合如下:

const userSchema = mongoose.Schema({
  _id: mongoose.Schema.Types.ObjectId,
  first_name: {
    type: String,
    required: true,
  },
  last_name: {
    type: String,
    required: true,
  },
  posts: [
    {
      id: {
        type: String,
        required: true,
      },
      title: {
        type: String,
        required: true,
      },
      content: {
        type: String,
        required: true,
      },
    }
  ],
});

module.exports = mongoose.model('dbUser', userSchema);

我正在尝试使用GraphQL突变将新条目推入文档的 posts [] 数组之一:

Mutation: {
    addPost: async (parent, args) => {
      let output = {};
      let output2 = {};
      const newpost = new dbPost({
        _id: new mongoose.Types.ObjectId(),
        title: args.title,
        content: args.content,
        author: {
          id: args.authorid,
          first_name: args.authorfirstname,
          last_name: args.authorlastname,
        }
      });
      const newpost2 = {
        id: args.id,
        title: args.title,
        content: args.content,
      };
      output = await newpost.save();
      output2 = await dbUser.findOneAndUpdate(
        { _id: args.authorid },
        { $push: { posts: newpost2 } },
        true
      );
      console.log(output2);
      return output;
    },
  },

如您所见,我正在尝试更新此突变中的两个不同的集合 dbPosts dbUsers dbPosts 的更新工作正常,但 dbUsers 上的更新似乎已失败。我看到的错误是:

  

“不能使用'in'运算符来真正搜索'useFindAndModify'”

我的findOneAndUpdate()语法有问题吗?

0 个答案:

没有答案