How to set _id to db document in Mongoose?

前端 未结 3 1497
长情又很酷
长情又很酷 2020-11-27 07:07

I\'m trying to dynamically create _id\'s for my Mongoose models by counting the documents in the db, and using that number to create the _id (assuming the first _id is 0). H

相关标签:
3条回答
  • 2020-11-27 07:45

    The first piece of @robertklep's code doesn't work for me (mongoose 4), also need to disabled _id

    var Post = new mongoose.Schema({
      _id: Number,
      title: String,
      content: String,
      tags: [ String ]
    }, { _id: false });
    

    and this works for me

    0 讨论(0)
  • 2020-11-27 07:49

    Create custom _id in mongoose and save that id as a mongo _id. Use mongo _id before saving documents like this.

    const mongoose = require('mongoose');
        const Post = new mongoose.Schema({
              title: String,
              content: String,
              tags: [ String ]
            }, { _id: false });
    
    // request body to save
    
    let post = new PostModel({
            _id: new mongoose.Types.ObjectId().toHexString(), //5cd5308e695db945d3cc81a9
            title: request.body.title,
            content: request.body.content,
            tags: request.body.tags
        });
    
    
    post.save();
    
    0 讨论(0)
  • 2020-11-27 07:50

    You either need to declare the _id property as part of your schema (you commented it out), or use the _id option and set it to false (you're using the id option, which creates a virtual getter to cast _id to a string but still created an _id ObjectID property, hence the casting error you get).

    So either this:

    var Post = new mongoose.Schema({
        _id: Number,
        title: String,
        content: String,
        tags: [ String ]
    });
    

    Or this:

    var Post = new mongoose.Schema({
        title: String,
        content: String,
        tags: [ String ]
    }, { _id: false });
    
    0 讨论(0)
提交回复
热议问题