node.js 如何在 Mongoose 中将 _id 设置为 db 文档?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19760829/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 16:10:43  来源:igfitidea点击:

How to set _id to db document in Mongoose?

javascriptnode.jsmongodbmongoose

提问by EmptyArsenal

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). However, I can't get the _id to set from my values. Here's my code:

我正在尝试通过计算数据库中的文档并使用该数字来创建 _id(假设第一个 _id 为 0)来为我的 Mongoose 模型动态创建 _id。但是,我无法从我的值中设置 _id。这是我的代码:

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

var count = 16;

//Models
var PostModel = mongoose.model( 'Post', Post );

app.post( '/', function( request, response ) {

    var post = new PostModel({
        _id: count,
        title: request.body.title,
        content: request.body.content,
        tags: request.body.tags
    });

    post.save( function( err ) {
        if( !err ) {
            return console.log( 'Post saved');
        } else {
            console.log( err );
        }
    });

    count++;

    return response.send(post);
});

I've tried to set the _id a number of different ways, but it's not working for me. Here's the latest error:

我尝试以多种不同的方式设置 _id,但它对我不起作用。这是最新的错误:

{ message: 'Cast to ObjectId failed for value "16" at path "_id"',
  name: 'CastError',
  type: 'ObjectId',
  value: 16,
  path: '_id' }

If you know what's going on, please let me know.

如果你知道发生了什么,请告诉我。

回答by robertklep

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

您要么需要将该_id属性声明为架构的一部分(您已将其注释掉),要么使用该_id选项并将其设置为false(您正在使用该id选项,该选项创建了一个虚拟 getter 来_id转换为字符串,但仍创建了一个_idObjectID属性,因此会出现铸造错误)。

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 });

回答by timqian

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

@robertklep 的第一段代码对我不起作用(mongoose 4),也需要禁用 _id

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

and this works for me

这对我有用

回答by jenish

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

在 mongoose 中创建自定义 _id 并将该 id 保存为 mongo _id。在保存这样的文档之前使用 mongo _id 。

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();