简体   繁体   中英

Saving an array (of 'tags') to MongoDB using Mongoose

I'm playing around with Mongoose and I'm having trouble saving to an array. For example, I have an input field on a page for comma-separated tags . I grab these from req.body.tags, remove the white space, and split them by the commas to get an array of the tags. Now, how do I save this array back to my database? I'm guessing I've set up this part of the schema wrong but I'm not sure what's right, to be honest. The schema I have so far is:

var postSchema = mongoose.Schema({
  title: String,
  permalink: String,
  content: String,
  author: {
    id: String,
    name: String,
  },
  postDate: {
    type: Date,
    default: Date.now
  },
});

If I was to save tags (from a post, for example) would it be best to have an array called tags and then each tag has a name (and id?)? If so, would I just add something like this (below) to the schema? The idea of adding tags to a post is so that I can display them (as links) on the post and be able to search the database for all posts with a certain tag. Is this the right way to go about it?

tags: [{
  name: String,
  id: String
}]

When posting to the new post route, I'm doing the following:

  post = new Post(req.body);
  tags = req.body.tags.replace(/\s/g,'').split(',');
  // maybe post.tags = tags ?    
  post.save(function(err) {
    if (!err) {
      res.redirect('/posts');
    } else {
      ...
    }
  });

This successfully saves all other fields submitted (title, author, content, etc.) but I'm not sure how I can save the newly-created tags back to the database. Any advice here would be very welcome as I'm new to this and keen to keep learning. Thanks!

If you really want your "tags" array to have a name field and a generated _id field then define another schema and embed it:

var tagSchema = mongoose.Schema({
    name: String
});

var postSchema = mongoose.Schema({
  title: String,
  permalink: String,
  content: String,
  author: {
    id: String,
    name: String,
  },
  postDate: {
    type: Date,
    default: Date.now
  },
  tags: [tagSchema]
});

Then manipulate the input to the correct structure before you create the Post object:

req.body.tags = req.body.tags.replace(/\s/''/g).split(",").map(function(tag) {
    return { "name": tag };
});

var post = new Post(req.body);

Or just leave it as an array of plain strings:

var postSchema = mongoose.Schema({
  title: String,
  permalink: String,
  content: String,
  author: {
    id: String,
    name: String,
  },
  postDate: {
    type: Date,
    default: Date.now
  },
  tags: [String]
});

And don't worry about mapping the object property:

req.body.tags = req.body.tags.replace(/\s/''/g).split(",");
var post = new Post(req.body);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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