Nodejs mongoose 子文档 数组操作

Nodejs mongoose 子文档 数组操作

 Article.findByIdAndUpdate(req.body.aid,{$set:{title:req.body.title,tags:req.body.tags,uid:req.body.uid,pv:req.body.pv}},function(err,Article){
if(!err){
if(!req.body.article){
Article.findByIdAndUpdate(Article._id,{$push:{Article:{collections:{
uid: req.body.uid,
time: req.body.time,
article: req.body.article.split("<!–p-->"),
}}}},function(err,Article){
if(!err){
res.send(‘数据更新成功’)
}
});
}
res.send(‘数据更新成功’)
}
});
{
“uid” : “4hg56f4hf”,
“title” : “f5sdf456sd”,
“tags” : “dfs,f,s,sdg,ds,gs,g,s,dg”,
“pv” : 0,
“_id” : ObjectId(“52da4efb5007465c1c16006e”),
“comments” : [],
“collections” : [{
“uid” : “4hg56f4hf”,
“time” : new Date(“2/1/1970 18:17:36”),
“_id” : ObjectId(“52da4efb5007465c1c16006f”),
“article” : [“j4f5gh4564h\r\nf5<!–page–>6sd4f564sf6h4s64h6sdhsh56sd26dsh56sh65s6+h56+sd5h5sd6+h56+<!–page–>sd5gf65f6h5fg6j4f4h5kjh54jh5f4f418451544156154845oiuyyurjkjhgfsdadfghjkjhgfdsasdfghjklkjhgfd”]
}],
“__v” : 0
}

##怎么在collections数组中添加一个集

{
 uid: req.body.uid,
 time: req.body.time,
 article: req.body.article.split("<!--p-->"),
}

6 回复

在使用 Mongoose 进行子文档数组操作时,经常需要向数组中添加新的子文档。以下是如何在 collections 数组中添加一个新元素的示例代码和解释。

示例代码

const mongoose = require('mongoose');
const Article = mongoose.model('Article', {
  title: String,
  tags: [String],
  pv: Number,
  uid: String,
  comments: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Comment' }],
  collections: [{
    uid: String,
    time: Date,
    article: [String]
  }]
});

// 更新文章信息并添加一个新的收藏
Article.findByIdAndUpdate(
  req.body.aid,
  {
    $set: {
      title: req.body.title,
      tags: req.body.tags.split(','),
      uid: req.body.uid,
      pv: req.body.pv
    },
    $push: {
      collections: {
        uid: req.body.uid,
        time: new Date(),
        article: req.body.article.split('<!--p-->')
      }
    }
  },
  { new: true },
  (err, updatedArticle) => {
    if (!err) {
      res.send('数据更新成功');
    } else {
      console.error(err);
      res.status(500).send('数据更新失败');
    }
  }
);

解释

  1. 定义 Schema:

    • 使用 Mongoose 定义了一个 Article 模型,并且定义了 collections 字段为一个包含多个对象的数组。
    • collections 数组中的每个对象包含 uid, timearticle 字段。
  2. 更新文档:

    • 使用 findByIdAndUpdate 方法来更新指定 _id 的文档。
    • $set 操作符用于更新 title, tags, uidpv 字段。
    • $push 操作符用于向 collections 数组中添加新的子文档。
  3. 处理请求体:

    • req.body.tags 字符串转换为数组。
    • 使用 split('<!--p-->') 方法将 req.body.article 字符串拆分为数组。
  4. 错误处理:

    • 如果更新成功,返回 “数据更新成功”。
    • 如果更新过程中发生错误,则记录错误并返回 “数据更新失败”。

通过这种方式,可以方便地向 collections 数组中添加新的子文档。希望这些示例代码和解释对你有所帮助!


楼主我现在也遇到这个问题,请问下,你是怎么解决的?

貌似没解决好像~

你查出来以后,找到collections节点添加节点,再存进去。 --------------------贴段代码可以参考一下---------------------- collection.findOne(user,function(err,value){ if(err) next(err); // console.log(value); //第一次添加数据到myTweetList集合中。需要创建一个对象 if(value == undefined || value == null){ // var insert_obj = obj; db.collection(collection_name,function(err,collection){ collection.insert(obj,{safe:safe},function(err,result){ // console.log('insert err = '+err+'value = '+value); next(err,result); }) }) }else{ //已经有数据了,需要更新数据 if(value.tweetlist == undefined || value.tweetlist == null){ value.tweetlist = new Array(); } for(var i = 0 ,length = obj.tweetlist.length;i<length ;i++){ var _u = { ‘tweetname’:obj.tweetlist[i].tweetname, ‘password’:obj.tweetlist[i].password }; value.tweetlist.push(_u); } db.collection(collection_name,function(err,collection){ collection.update(user,value,{safe:safe},function(err){ next(err,value); }) }) } })

好像可以通过 $push或者 $addToSet进行操作数组集合 通过mongoDB直接操作,例子: > db.blog.update({“title”:“one blog”}, {"$push": {“comments”:{“content”:“word”}} > db.blog.findOne() { "_id" : ObjectId(“4fcd909520668578cc1097dc”), “comments” : [ { “content” : “hello” }, { “content” : “word” } ], “title” : “one blog” }

要在 collections 数组中添加一个新的子文档,你可以使用 Mongoose 的 $push 操作符。下面是修改后的代码示例:

Article.findByIdAndUpdate(
  req.body.aid,
  {
    $set: {
      title: req.body.title,
      tags: req.body.tags.split(','),
      uid: req.body.uid,
      pv: req.body.pv
    },
    $push: {
      collections: {
        uid: req.body.uid,
        time: req.body.time,
        article: req.body.article.split("<!--p-->")
      }
    }
  },
  function (err, updatedArticle) {
    if (!err) {
      res.send('数据更新成功');
    } else {
      console.error(err);
      res.status(500).send('数据更新失败');
    }
  }
);

解释

  1. $set: 更新文章的基本信息,如 title, tags, uid, 和 pv
  2. $push: 将新的 collections 子文档推送到 collections 数组中。
  3. 处理逻辑:
    • 如果更新成功,则返回 数据更新成功
    • 如果发生错误,则记录错误并返回 数据更新失败

注意点

  • 确保 tags 字符串被正确地转换为数组(例如,通过 split(','))。
  • uidtime 应该是从请求体中获取的有效值。
  • article 字符串应被分割成数组以便存储。

这样可以确保在 collections 数组中正确添加一个新的子文档。

回到顶部