【问题标题】:Add a field to existing MongoDB document (with Mongoose in Node.js)向现有 MongoDB 文档添加一个字段(在 Node.js 中使用 Mongoose)
【发布时间】:2014-07-20 11:46:12
【问题描述】:

我在 MongoDB 数据库的集合 Article 中有这个现有文档:

[ { site: 'www.atlantico.fr',
date: '2014-05-27T11:10:19.000Z',
link: 'http://www.atlantico.fr/example.html',
_id: 538473817eb00f082f4803fc,
__v: 0} ]

我想使用 Node.js 中的 Mongoose 在此文档中添加一个值为 'example' 的新字段 day。所以我这样做:

Article.update(
      { link: 'http://www.atlantico.fr/example.html'}, 
      { $set : {day : 'example'} }, 
       function(err){  
                    });

但它不起作用,因为当我在那之后查询文档时,没有新字段day出现......

我在 Mongoose 中使用 update$set 时一定犯了一个错误,但我找不到确切的错误。

我错过了什么?谢谢!

【问题讨论】:

  • 请显示文章的猫鼬模型
  • 一开始我在模式和模型中都没有day 字段。

标签: javascript node.js mongodb mongoose updates


【解决方案1】:

试试

Article.update(
     {link: 'http://www.atlantico.fr/example.html'}, 
     {day : 'example' },
     {multi:true}, 
       function(err, numberAffected){  
       });

并且不要忘记在架构中添加日期。

【讨论】:

  • 在模式中获取它的提醒特别有用。
【解决方案2】:
Article.findByIdAndUpdate(id, { $set: { day: 'example' }}, { new: true }, function (err, article) {
  if (err) return handleError(err);
  res.send(article);
});

我更喜欢这种方式,因为它包含一个回调函数。

参考和更多信息:http://mongoosejs.com/docs/documents.html

【讨论】:

    【解决方案3】:
    await Users.updateOne( {link: 'http://www.atlantico.fr/example.html'},{ $set: { day : 'example'} }, { multi: true });
    
    • 不推荐使用更新
    • 使用 await 进行数据库操作
    • 如果你想在集合中添加新的文件,首先检查它是否被添加到模型中 (如果您不想使用该文件作为强制制作,则为“必需:false”)

    【讨论】:

      猜你喜欢
      • 2023-02-14
      • 2017-06-26
      • 1970-01-01
      • 2012-10-27
      • 2020-07-31
      • 2020-12-08
      • 1970-01-01
      • 2013-01-15
      • 2021-06-04
      相关资源
      最近更新 更多