【发布时间】:2021-01-12 11:53:51
【问题描述】:
我有两个 MongoDB 集合,如下所示,(一个图书馆只有一本书用于演示目的):
// books
| _id | author | title |
| ObjectID("yyy") | jean | foo |
| ObjectID("yyy") | paul | bar |
| ObjectID("yyy") | baz | boo |
// library
| _id | name | book |
| ObjectID("xxx") | foobar | ObjectID("yyy") |
| ObjectID("xxx") | pagez | ObjectID("yyy") |
| ObjectID("xxx") | booky | ObjectID("yyy") |
我为这样的库制作了一个架构
export const LibrarySchema = new Schema({
name: {
type: String,
required: true,
},
book: {
_id: false,
type: Schema.Types.ObjectId, // (1)
ref: "Book" // yes, the schema is registered properly, it's called `Book`
}
})
(1) 我有 ObjectID,因为(如集合中所示)这本书与 objectid 引用一起存储,如果我将它们更改为书籍架构,它将找不到它们在填充时不再存在。
现在,问题来了,我的目标是拥有一个包含所有图书馆及其书籍的原始集合,如下所示:
// library_complete
| _id | name | book |
| ObjId("xxx") | foobar | { author: "jean", title: "foo"} |
| ObjId("xxx") | booky | { author: "baz", title: "boo"} |
(请不要问我为什么需要原始(嵌入式)集合,我已经复制了我的目标以尽可能容易理解,并且绝对有必要拥有原始(嵌入式)集合) em>
原始库集合的架构如下:
const RawLibrarySchema = new Schema({
name: {
type: String,
required: true
},
book: {
_id: false,
type: BookSchema, // changing this to `Object` doesn't work either
}
})
现在,我想在服务中创建一本书
const linkLibaryToBook = async (library, bookId) => {
// some complex calculations to link library to books and populates it
const libraryBook = await someComplexFunction(library, bookId); // in this function the book gets populated, see the return type below
console.log(libraryBook);
/* @returns
libraryBook {
name: "foobar",
book: { author: "jean", title: "foo" },
}
*/
saveRawLibrary(libraryBook);
}
上面的返回类型正是我想要实现的,现在当我像下面这样写掉它时
const saveRawLibrary = async (libraryObject) => {
console.log(libraryObject);
/* @returns
libraryBook {
name: "foobar",
book: { author: "jean", title: "foo" },
}
// ^ this is as it should be ^
*/
const _library = new libraryModel(libraryObject);
console.log(_library);
/* @returns
_library {
name: "foobar",
book: "9023920dada032aa" // the objectId of the original book
}
// ^ this is what comes out ^
*/
}
突然之间,mongoose 将书的 ID 链接到了图书馆而不是对象。我只想像前两个控制台日志中所示那样写出普通对象。我也尝试过使用这样的普通创建:
const saveRawLibrary = async (libraryObject) => {
await libraryModel.create(libraryObject);
}
但是,这完全一样,它只是用 id 引用它......有没有办法直接插入一个对象?想看实物和结果的可以click here。
TL;DR; 我有一个想要写掉的 JavaScript 对象,但如果我这样做,它会神奇地分配 objectIDs 而不是原始对象。
【问题讨论】:
-
你必须使用填充方法。
-
我愿意,请阅读该方法返回的控制台日志。
-
你能发布你的 bookSchema 吗?
-
嗯,它只是一个带有作者字符串和标题字符串的架构,仅此而已
-
我在函数中添加了一些 cmets,以便更清楚地了解它们的作用,请看一下 :)
标签: javascript node.js mongodb mongoose