我有一个带有用户和发布模型的简单应用,

var mongoose = require("mongoose");
mongoose.connect("mongodb://localhost/assoc", {useMongoClient:true});
mongoose.Promise = global.Promise;

//Post
var postSchema = new mongoose.Schema({
    title: String,
    content: String
});
var Post = mongoose.model("Post", postSchema);

//User
var userSchema = new mongoose.Schema({
    email: String,
    name: String,
    posts: [postSchema]
});

var User = mongoose.model("User", userSchema);

我之前创建了一个用户(名称:“gino”),并将帖子发布到:
// var newUser = new User({
//     email: "[email protected]",
//     name: "gino"
// });
//
// newUser.posts.push({
//     title: "gino's post",
//     content: "this is content"
// });
//
// newUser.save(function (err, user) {
//     if (err) {
//         console.log(err);
//     } else {
//         console.log(user);
//     }
// });

还创建另一个帖子以检查帖子模型是否有效:
// var newPost = new Post({
//     title: "honky",
//     content: "tonky"
// });
//
// newPost.save(function (err, post) {
//     if (err) {
//         console.log(err);
//     } else {
//         console.log(post);
//     }
// });

当我尝试找到“gino”并将新项目推送到posts数组中时,尝试使用此代码段保存用户(user.save)时出现错误:
User.findOne({name: "gino"}, function (err, user) {
    if (err) {
        console.log(err);
    } else {
        console.log(user);
        user.posts.push({
            title: "post",
            content: "content"
        });
        user.save(function (err, user) {
            if (err) {
                console.log(err);
            } else {
                console.log(user);
            }
        });
    }
});

当我运行该应用程序时,我得到了以下信息:
{ MongoError: Unknown modifier: $pushAll
    at Function.MongoError.create (appFolder\node_modules\mongodb-core\lib\error.js:31:11)
    at toError (appFolder\node_modules\mongodb\lib\utils.js:139:22)
    at appFolder\node_modules\mongodb\lib\collection.js:1059:67
    at appFolder\node_modules\mongodb-core\lib\connection\pool.js:469:18
    at _combinedTickCallback (internal/process/next_tick.js:131:7)
    at process._tickCallback (internal/process/next_tick.js:180:9)
  name: 'MongoError',
  message: 'Unknown modifier: $pushAll',
  driver: true,
  index: 0,
  code: 9,
  errmsg: 'Unknown modifier: $pushAll' }

有人可以帮助我吗?

最佳答案

尝试改用findOneAndUpdate

User.findOneAndUpdate(
  { name: "gino" },
  { $push: { posts: { title: 'post', content: 'content' } } },
  { new: true },
  function (err, user) {
    if(err) console.log("Something wrong when updating data");
    console.log(user);
});

希望能帮助到你!

09-25 17:46