Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mongoose在嵌套子文档中推入数组_Mongoose_Updates - Fatal编程技术网

Mongoose在嵌套子文档中推入数组

Mongoose在嵌套子文档中推入数组,mongoose,updates,Mongoose,Updates,我有这个模式: var UserSchema = new Schema({ profile: { firstName: {type: String, trim: true, required: true }, lastName: {type: String, trim: true, required: true }, city: {type: String} age: {type: Number, min: 13, max: 120}, image:

我有这个模式:

var UserSchema = new Schema({
  profile: {
    firstName: {type: String, trim: true, required: true },
    lastName: {type: String, trim: true, required: true },
    city: {type: String}
    age: {type: Number, min: 13, max: 120},
    image: {type: String,trim: true}
  },
  friends:{
    accepted:[{
       id: {type: mongoose.Schema.Types.ObjectId, ref: 'User'},
       dateAccepted: {type: Date, default: Date.now}
    }]
  }
}
如何在friends.accepted with.update方法中推送数据

我只有使用findOne方法才能成功:

User.findOne({
  _id: id
  },function(err,user){
    user.friends.accepted.push(newUser._id);
    user.save(function(err){if(err) return err;})
  });
这应该起作用:

User.findOneAndUpdate({
  _id: id
}, {
  $push: {
    "friends.accepted": {
      id: newUser._id
    }
  }
},
{
  new: true
},
function (err, user) {
  console.log(err, user);
});
您也可以使用User.update,但回调的第二个参数将是更新查询的结果:
{ok:1,nModified:1,n:1}


使用允许您获取用户对象。通过在选项中传递
new:true
可以获得更新的用户对象,而如果没有它,则可以获得原始对象。

我找到了答案,有了更新,它是_id:newUser。_id,即使在我的模型中它是id