node.js 如何在 mongoose 中将 ObjectId 设置为数据类型

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8111846/
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 14:46:07  来源:igfitidea点击:

How to set ObjectId as a data type in mongoose

node.jsmongoose

提问by idophir

Using node.js, mongodb on mongoHQ and mongoose. I'm setting a schema for Categories. I would like to use the document ObjectId as my categoryId.

在 mongoHQ 和 mongoose 上使用 node.js、mongodb。我正在为类别设置架构。我想使用文档 ObjectId 作为我的 categoryId。

var mongoose = require('mongoose');

var Schema = mongoose.Schema,
    ObjectId = Schema.ObjectId;
var Schema_Category = new Schema({
    categoryId  : ObjectId,
    title       : String,
    sortIndex   : String
});

I then run

然后我跑

var Category = mongoose.model('Schema_Category');
var category = new Category();
category.title = "Bicycles";
category.sortIndex = "3";

category.save(function(err) {
  if (err) { throw err; }
  console.log('saved');
  mongoose.disconnect();     
});

Notice that I don't provide a value for categoryId. I assumed mongoose will use the schema to generate it but the document has the usual "_id" and not "categoryId". What am I doing wrong?

请注意,我没有为 categoryId 提供值。我假设 mongoose 将使用模式来生成它,但文档具有通常的“_id”而不是“categoryId”。我究竟做错了什么?

回答by addisonj

Unlike traditional RBDMs, mongoDB doesn't allow you to define any random field as the primary key, the _id field MUST exist for all standard documents.

与传统的 RBDM 不同,mongoDB 不允许您定义任何随机字段作为主键,所有标准文档都必须存在 _id 字段。

For this reason, it doesn't make sense to create a separate uuid field.

因此,创建单独的 uuid 字段没有意义。

In mongoose, the ObjectId type is used not to create a new uuid, rather it is mostly used to reference other documents.

在 mongoose 中,ObjectId 类型不用于创建新的 uuid,而是主要用于引用其他文档。

Here is an example:

下面是一个例子:

var mongoose = require('mongoose');

var Schema = mongoose.Schema,
    ObjectId = Schema.ObjectId;
var Schema_Product = new Schema({
    categoryId  : ObjectId, // a product references a category _id with type ObjectId
    title       : String,
    price       : Number
});

As you can see, it wouldn't make much sense to populate categoryId with a ObjectId.

如您所见,使用 ObjectId 填充 categoryId 没有多大意义。

However, if you do want a nicely named uuid field, mongoose provides virtual properties that allow you to proxy (reference) a field.

但是,如果您确实想要一个命名良好的 uuid 字段,mongoose 提供了允许您代理(引用)一个字段的虚拟属性。

Check it out:

一探究竟:

var mongoose = require('mongoose');

var Schema = mongoose.Schema,
    ObjectId = Schema.ObjectId;
var Schema_Category = new Schema({
    title       : String,
    sortIndex   : String
});

Schema_Category.virtual('categoryId').get(function() {
    return this._id;
});

So now, whenever you call category.categoryId, mongoose just returns the _id instead.

所以现在,每当您调用 category.categoryId 时,mongoose 只会返回 _id。

You can also create a "set" method so that you can set virtual properties, check out this linkfor more info

您还可以创建一个“设置”方法,以便您可以设置虚拟属性,查看此链接了解更多信息

回答by jpenna

I was looking for a different answer for the question title, so maybe other people will be too.

我正在为问题标题寻找不同的答案,所以也许其他人也会如此。

To set type as an ObjectId (so you may reference authoras the author of book, for example), you may do like:

要将 type 设置为 ObjectId(例如,您可以author作为 的作者引用book),您可以这样做:

const Book = mongoose.model('Book', {
  author: {
    type: mongoose.Schema.Types.ObjectId, // here you set the author ID
                                          // from the Author colection, 
                                          // so you can reference it
    required: true
  },
  title: {
    type: String,
    required: true
  }
});

回答by devcodex

My solution on using ObjectId

我使用 ObjectId 的解决方案

// usermodel.js

const mongoose = require('mongoose')
const Schema = mongoose.Schema
const ObjectId = Schema.Types.ObjectId


let UserSchema = new Schema({
   username: {
     type: String
   },
   events: [{
     type: ObjectId,
     ref: 'Event' // Reference to some EventSchema
   }]
})

UserSchema.set('autoIndex', true)

module.exports = mongoose.model('User', UserSchema)

Using mongoose's populatemethod

使用猫鼬的填充方法

// controller.js

const mongoose = require('mongoose')
const User = require('./usermodel.js')

let query = User.findOne({ name: "Person" })

query.exec((err, user) => {
  if (err) {
     console.log(err)
  }

  user.events = events
  // user.events is now an array of events
})

回答by Chukwuma Nwaugha

The solution provided by @dex worked for me. But I want to add something else that also worked for me: Use

@dex 提供的解决方案对我有用。但我想添加一些对我有用的东西:使用

let UserSchema = new Schema({
   username: {
     type: String
   },
   events: [{
     type: ObjectId,
     ref: 'Event' // Reference to some EventSchema
   }]
})

if what you want to create is an Array reference. But if what you want is an Object reference, which is what I think you might be looking for anyway, remove the brackets from the valueprop, like this:

如果您要创建的是 Array 引用。但是,如果您想要的是 Object 引用,我认为您可能正在寻找,请从value道具中删除括号,如下所示:

let UserSchema = new Schema({
   username: {
     type: String
   },
   events: {
     type: ObjectId,
     ref: 'Event' // Reference to some EventSchema
   }
})

Look at the 2 snippets well. In the second case, the value prop of key events does not have brackets over the object def.

好好看看这两个片段。在第二种情况下,关键事件的 value 属性在对象 def 上没有括号。