MongooseJS - 具有现有引用的Model.create

问题描述 投票:0回答:1

我正在尝试使用model.create()速记来创建一个具有现有User ObjectId的新公司。

const userSchema = new mongoose.Schema({
    firstName: String,
    lastName: String
});

const companySchema = new mongoose.Schema({
    companyName: String,
    users: [{
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User'
    }]
});

const User = mongoose.model('user2', userSchema);
const Company = mongoose.model('company2', userSchema);

users集合中已存在以下用户

{"_id":"5a9633031fe445041c07afd3","firstName":"John","lastName":"Doe","__v":0}

现在我想用这个现有用户创建一个新公司:

Company.create({
  companyName: 'Foo, Inc.',
  users: {5a9633031fe445041c07afd3}
}).then(function(err, company) {
  console.log(err, company);
});

我尝试过用户的变体:

users: '5a9633031fe445041c07afd3'
users: [5a9633031fe445041c07afd3]
users: [{5a9633031fe445041c07afd3}]

我该如何保存这份文件?

javascript mongodb mongoose
1个回答
0
投票

试试这个

let model = new Company();
const body = {
    companyName: 'Foo, Inc.',
    users: "5a9633031fe445041c07afd3"
};
model = Object.assign(model, body);
model.then((company) => {
    console.log(company);
}).catch((err) => {
    console.log(err);
})
© www.soinside.com 2019 - 2024. All rights reserved.