我有一个叫做people的mongodb集合 其架构如下:

people: {
         name: String, 
         friends: [{firstName: String, lastName: String}]
        }

现在,我有一个非常基本的快速应用程序连接到数据库,并成功地创建“人”与一个空的朋友数组。

在应用程序的次要位置,有一个添加好友的表单。表单接收firstName和lastName,然后是带有名称字段的POSTs,同样用于引用适当的people对象。

我有一个困难的时间做的是创建一个新的朋友对象,然后“推”到朋友数组。

我知道当我通过mongo控制台这样做时,我使用$push作为查找标准后的第二个参数的更新函数,但我似乎找不到合适的方法让猫鼬这样做。

db.people.update({name: "John"}, {$push: {friends: {firstName: "Harry", lastName: "Potter"}}});

当前回答

这就是你如何推送一个项目——官方文档

const schema = Schema({ nums: [Number] });
const Model = mongoose.model('Test', schema);

const doc = await Model.create({ nums: [3, 4] });
doc.nums.push(5); // Add 5 to the end of the array
await doc.save();

// You can also pass an object with `$each` as the
// first parameter to use MongoDB's `$position`
doc.nums.push({
  $each: [1, 2],
  $position: 0
});
doc.nums;

其他回答

推到嵌套字段-使用点符号

对于任何想知道如何推到嵌套字段时,例如这个Schema。

const UserModel = new mongoose.schema({
  friends: {
    bestFriends: [{ firstName: String, lastName: String }],
    otherFriends: [{ firstName: String, lastName: String }]
  }
});

你只需使用点符号,像这样:

const updatedUser = await UserModel.update({_id: args._id}, {
  $push: {
    "friends.bestFriends": {firstName: "Ima", lastName: "Weiner"}
  }
});

假设,var friend = {firstName: 'Harry', lastName: 'Potter'};

你有两个选择:

更新内存中的模型,并保存(简单的javascript array.push):

person.friends.push(friend);
person.save(done);

or

PersonModel.update(
    { _id: person._id }, 
    { $push: { friends: friend } },
    done
);

在可能的情况下,我总是尝试选择第一个选项,因为它会尊重mongoose给你的更多好处(钩子、验证等)。

然而,如果你正在进行大量的并发写操作,你就会遇到竞态条件,你最终会出现讨厌的版本错误,阻止你每次替换整个模型,并失去你之前添加的朋友。所以只有在绝对必要的情况下才会选择后者。

就我而言,我是这样做的

  const eventId = event.id;
  User.findByIdAndUpdate(id, { $push: { createdEvents: eventId } }).exec();

这就是你如何推送一个项目——官方文档

const schema = Schema({ nums: [Number] });
const Model = mongoose.model('Test', schema);

const doc = await Model.create({ nums: [3, 4] });
doc.nums.push(5); // Add 5 to the end of the array
await doc.save();

// You can also pass an object with `$each` as the
// first parameter to use MongoDB's `$position`
doc.nums.push({
  $each: [1, 2],
  $position: 0
});
doc.nums;

$push操作符将指定的值附加到数组中。

{ $push: { <field1>: <value1>, ... } }

$push将数组字段的值添加为其元素。

上面的答案满足所有的要求,但我通过做以下工作

var objFriends = { fname:"fname",lname:"lname",surname:"surname" };
People.findOneAndUpdate(
   { _id: req.body.id }, 
   { $push: { friends: objFriends  } },
  function (error, success) {
        if (error) {
            console.log(error);
        } else {
            console.log(success);
        }
    });
)