简体   繁体   English

仅返回猫鼬数组中的一项?

[英]Returning only one item of an array in mongoose?

I am trying to grab one array element and update a bunch of it's properties. 我正在尝试获取一个数组元素并更新一堆属性。 Here is how I am currently doing it which feels like the wrong way to me. 这是我目前正在做的事情,感觉对我来说是错误的方式。 Can this be done without having to loop through the array to match the _id? 是否可以不必遍历数组以匹配_id来完成此操作? Can you select just one of the array elements by _id to be updated? 您能否仅通过_id选择要更新的数组元素之一?

Schemas.Users.findOne({ _id: req.session.userID })
.select('friends').exec(function(err, user){
  if (err) return next(err);

  // figure out which friend I should be updating
  var index = null;
  for (var i = 0; i < user.friends.length; i++) {
    if (user.friends[i]._id == req.params.friendID) {
      index = i;
      break;
    }
  }

  // if we didn't find the friend, something went wrong
  if (index === null) {
    console.log('Error: index not found.');
    return res.redirect('somepage');                
  }

  // update friend
  user.friends[index].name = req.body.name;

  user.markModified('friends');
  user.save();

  return res.redirect('somepage');
});

Yes, Mongoose have an id method designed especially for your case: 是的,猫鼬有专门针对您的情况设计的id方法:

Schemas.Users.findOne({
  _id: req.session.userID,
}).select('friends').exec(function(err, user){
  if (err) return next(err);

  var friend = user.friends.id(req.params.friendID);

  // if we didn't find the friend, something went wrong
  if (friend === null) {
    console.log('Error: index not found.');
    return res.redirect('somepage');                
  }

  // update friend
  friend.name = req.body.name;

  user.save();

  return res.redirect('somepage');
});

If your only goal it to set the name of the user's friend, then you may consider using update instead of findOne and save : 如果您的唯一目标是设置用户朋友的名字,那么您可以考虑使用update而不是findOnesave

Schemas.Users.update({
  _id: req.session.userID,
  friends: {$elemMatch: {
    _id: req.params.friendID
  }}
}, {
  'friends.$.name': req.params.friendID
}).exec(function(err, numberAffected){
  if (err) return next(err);

  // if we didn't find the friend, something went wrong
  if (numberAffected === 0) {
    console.log('Error: index not found.');
    return res.redirect('somepage');                
  }

  return res.redirect('somepage');
});

Update is faster, but Mongoose setters , validators and middlewares don't work with it. Update速度更快,但是Mongoose的settersvalidatorsmiddlewares不能使用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM