关于mongoose的ObjectId设置问题 Nodejs

关于mongoose的ObjectId设置问题 Nodejs

mongoose.Schema.Types.ObjectId这个是现在官方API获得ObjectId的方法, mongoose.Schema.ObjectId这个是是原来2012年6月份以前获得ObjectId的方法, 我用下面的schema试了下, var UserScheme = new Schema({ userId:ObjectId, username:String, password:String, userAccountId:ObjectId, userAccountSummary:{type:String,default:“1000”}, myProjectsList:[], myCommentsList:[Comments], myFundedProjectsList:[]

}); 为什么后期数据库总是查不到userId和userAccountId,它被设定为ObjectId啊,数据库应该自动分配给它一个值,但是数据库没有。截图如下。enter image description here

请求解释下


4 回复

在Mongoose中,mongoose.Schema.Types.ObjectId 是用于定义字段类型为 ObjectId 的正确方式。而 mongoose.Schema.ObjectId 已经在较新的版本中被弃用了。

你提到的问题可能是由于以下几个原因:

  1. 初始化问题:在创建文档时,如果没有给 userIduserAccountId 字段赋值,它们将默认为 nullundefined
  2. 默认值问题:如果你希望这些字段在创建文档时自动生成一个 ObjectId,你需要在创建文档时显式地为其赋值,或者使用 default 函数来生成。

示例代码

假设你希望在创建用户文档时自动生成 userIduserAccountId,可以这样做:

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

// 定义Schema
const UserSchema = new Schema({
    userId: { type: Schema.Types.ObjectId, default: mongoose.Types.ObjectId },
    username: String,
    password: String,
    userAccountId: { type: Schema.Types.ObjectId, default: mongoose.Types.ObjectId },
    userAccountSummary: { type: String, default: "1000" },
    myProjectsList: [{ type: Schema.Types.ObjectId }],
    myCommentsList: [{ type: Schema.Types.ObjectId }],
    myFundedProjectsList: [{ type: Schema.Types.ObjectId }]
});

// 创建模型
const User = mongoose.model('User', UserSchema);

// 创建用户实例
async function createUser() {
    const newUser = new User({
        username: 'testUser',
        password: 'testPassword'
    });

    await newUser.save();
    console.log(newUser);
}

createUser().catch(err => console.error(err));

解释

  1. 定义Schema

    • userIduserAccountId 字段都定义为 ObjectId 类型,并且设置了默认值为 mongoose.Types.ObjectId
  2. 创建模型

    • 使用定义的 UserSchema 创建了一个 User 模型。
  3. 创建用户实例

    • 在创建用户实例时,不需要手动指定 userIduserAccountId,因为它们会自动使用默认值(即生成一个新的 ObjectId)。

通过这种方式,你可以确保每次创建用户时,userIduserAccountId 都会被正确地自动生成并填充到数据库中。


mongoose如何自己设置ObjectId,我在官网没查到,知道的请解释下

哎,这个问题一看就很清晰了。 申明:ObjectId不是指主键,他只是mongodb中的一种主键类型。 因此,你定义的Schema虽然有很多ObjectId类型,但是却没有指定谁是真正的主键。程序无法得知你定义的真正主键是谁,还是会为你默认分配_id作为你的主键,他的类型是ObjectId。程序只会给真正的主键赋值,其他的2个当然不会给值咯。如果你想给他值,就要写set方法,让Schema构造完后写入数据库时自动生成值。

在Mongoose中,mongoose.Schema.Types.ObjectId 是用于定义 ObjectId 类型字段的标准方法。mongoose.Schema.ObjectId 已经被弃用了,因此不建议再使用。

对于你提到的 userIduserAccountId 字段无法自动填充 ObjectId 的问题,可能是因为这些字段没有设置默认值或自动生成策略。Mongoose 默认不会自动为这些字段生成 ObjectId,你需要显式地指定如何处理这些字段。

示例代码

const mongoose = require('mongoose');
const { Schema } = mongoose;

// 创建Schema
const UserSchema = new Schema({
    userId: { type: Schema.Types.ObjectId, default: mongoose.Types.ObjectId },
    username: String,
    password: String,
    userAccountId: { type: Schema.Types.ObjectId, default: mongoose.Types.ObjectId },
    userAccountSummary: { type: String, default: "1000" },
    myProjectsList: [{ type: Schema.Types.ObjectId }],
    myCommentsList: [{ type: Schema.Types.ObjectId }],
    myFundedProjectsList: [{ type: Schema.Types.ObjectId }]
});

// 创建Model
const User = mongoose.model('User', UserSchema);

// 使用Model
(async () => {
    await mongoose.connect('mongodb://localhost:27017/testdb', { useNewUrlParser: true, useUnifiedTopology: true });

    // 创建一个新的用户
    const newUser = new User({
        username: 'testuser',
        password: 'testpass'
    });

    await newUser.save();
    console.log(newUser);
})();

解释

  • UserSchema 中,userIduserAccountId 字段被定义为 ObjectId 类型,并且设置了默认值为 mongoose.Types.ObjectId()
  • 这样,当创建新用户时,如果 userIduserAccountId 没有被显式赋值,Mongoose 将会自动为其生成一个 ObjectId
  • 其他数组类型的字段也被定义为 ObjectId 类型,这样可以方便地存储关联的数据。

通过这种方式,你可以确保 userIduserAccountId 字段在创建新用户时自动填充 ObjectId

回到顶部